The standard LINQ .Distinct() function will pass your IEnumerable items to the ‘default comparer’ to differenciate the items.
If your IEnumerable contains objects of an arbitrary class you would ordinarily have to create a IEqualityComparer to compare the relavent property of each instance.
This seems like too much work just to simply remove objects that have a duplicate property value.
I came up with a workaround for this using the ‘group’ keyword to group your objects by the target property and to then select the first record from each group, using the ‘First’ extension.
C# Example:
var distinctByWeekNum = from e in allUserEntries group e by e.WeekNumber into g select g.First();
The above example basically selects all objects that are distinct based on the ‘WeekNumber’, by first grouping items with the same ‘WeekNumber’ together and then selecting only the first item from each group (thus dropping any duplicates).
Wonderfull solution..:). saved my few hours. thanks a lot. keep up the good work
.
Well it’s been ages since this post was created, but still it was incredibly useful, and I feel I must say thanks. after significant amount of time spent searching the web I finally found what i was looking for.. simple, elegant and to the point. saved me a hole lot of time
cheers
I’ve been hunting for hours for a simple solution like this, works a treat thanks! I wonder what the performance overheads are like?
SingingEels, your trick works nicely for LINQ to Objects, but won't work well for LINQ to SQL, LINQ to Entities, and the like. Craig's solution is the best when using those technologies.
Very cool trick! – I personally like extending the framework where I see it needs to be… here’s a more ‘deliberate’ way of doing a linq distinct based on a property. (basically achieves the same thing)