Ben
Ben

Reputation: 3912

Linq to object - Select Distinct

I can't quite figure out why this Linq Statement isn't working as i would expect:

    Dim distinctSurchargesList = (From thisparent As Parent In ThisParentCollection _
                                    From thisChild As Child In thisparent.theseChildren _
                                    Select New With {.childId = thischild.Id}).Distinct()

I would assume that this would create a new collection of anonymous types, that would be distinct. Instead it creates a collection the size of the "ThisParentCollection" with duplicate "MyAnonymousType" in it (duplicate id's).

Can anyone tell me where im going wrong?

Thanks

Upvotes: 1

Views: 1230

Answers (1)

Winston Smith
Winston Smith

Reputation: 21882

Your collection of anonymous types will be compared for equality by reference value - not by the value of the childId field. Each anonymous type will have a different object reference, hence they are all distinct.

Just select the ID, and don't project it into an anonymous type.

Upvotes: 4

Related Questions