Monday, February 15, 2010

Distinct? More like "dis stinks!"

So you are using LINQ and you have a list of of your class objects, but you need to be sure that you do not have duplicates in your list. You can't use the built in "Distinct" function because you have not built a comparator for your class. Should you iterate through all the element of the list while creating a temporary list? No. that's just dumb.

Do this instead: use GroupBy and then Select the first element of each group.

an example would look like this:

sampleObjects =
sampleObjects.GroupBy(d => d.SampleObjectId).Select(d => d.First());


Just be sure that on what ever field you perform the "GroupBy" menthod, it is the primary key property of that object.