Page 1 of 1

LINQ Distinct Operator

Posted: Wed 20 May 2009 13:54
by Colbotron
I have a Linq query and I want to remove duplicate entries based on a certain field

Code: Select all

            persons = From p In db.Persons, a In db.Addresses _
                      Where p.Id = a.PersonId _
                      Order By p.Id _
                      Select New With {p.EmailAddress, p.LastName, p.FirstName, a.Id, a.Phone1, _
                                       .PersonId = p.Id, .Department = p.Department.Name, p.Title}
I would like to remove entries with duplicate personIds (p.Id).
How can i achieve this in VB?

Posted: Thu 21 May 2009 11:53
by AndreyR
You can simply append the Distinct() method to your query.
But please note that you will need to implement your own IEqualityComparer class,
comparing Id properties of two Person instances only, because the default comparer uses the reference comparison.
The example is available here:
http://msdn.microsoft.com/en-us/library/bb338049.aspx