Question Duplicate Return

arabgogs

Member
Joined
Nov 6, 2012
Messages
14
Location
Scotland
Programming Experience
5-10
Hi Guys,
I am having an issue with a Linq Query I am using where it is returning more objects than I am actually starting off with.
this is the scenario I have and the code example



Dim arrs As IEnumerable(Of Entity.myObj) = From x In myOBJ.obj _
From x2 In x.stringList Where compareList.Contains(x2.str) _
Select x

myOBJ.obj is a list of objects and within each obj there is a list of strings (stringList) and compareList is also a list of strings that I use to compare against the stringList.

MY problem

I am getting a duplicate myOBj.Obj returned. I am unsure why it is duplicating the return and would be grateful of any help, as to why the WHERE clause compare returning a duplicate of the structure.

I hope that is clear enough.

Thanks for any help
 
You're joining two lists so the you're multiplying the number of items. Don't use From twice if you don't want to perform a join. Your query should be:
VB.NET:
From x In myOBJ.obj
Where x.stringList.Any(Function(x2) compareList.Contains(x2.str))
Select x
 
Note that two From clauses are not actually a join, they are just a compound From, like nested loops. A join implies a relationship, two From clauses does not. You could actually have used a join here, IF you wanted to match the records in two lists containing the same value.

From x In List1
From y In List2
Select x

is the same as
For Each x In List1
    For Each y In List2
        OutputList.Add(x)
    Next
Next


A join works differently:
From x In List1
Join y In List2 On x Equals y
Select x

is the same as:
For Each x in List1
    If List2.Contains(x) Then
        OutputList.Add(x)
    End If
Next
 
Last edited:
Note that two From clauses are not actually a join, they are just a compound From, like nested loops. A join implies a relationship, two From clauses does not.
It's a cross join if there's no specific relationship, although the relationship is inherent in this case because the second list is a property of the item from the first.
 
Back
Top