CraigWardman.com

[ LINQ Select Distinct on Custom Class Property ]

/Blog/Post

A catalogue of my discoveries in software development and related subjects, that I think might be of use or interest to everyone else, or to me when I forget what I did!

LINQ Select Distinct on Custom Class Property

Tuesday, 18 November 2008


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).

Labels: , ,

Share This!



2 Comments:

Blogger SingingEels.com said...

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)

11 Mar 2009 12:26:00  
Blogger  said...

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.

13 Oct 2009 16:25:00  

Post a Comment

<< Home

CraigWardman.com