CraigWardman.com

[ LINQ Select Distinct on Custom Class Property ]

/Blog/Post

LINQ Select Distinct on Custom Class Property

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

Share This!

5 Comments to LINQ Select Distinct on Custom Class Property

  1. Junaid's Gravatar Junaid
    December 19, 2011 at 12:29 pm | Permalink

    Wonderfull solution..:). saved my few hours. thanks a lot. keep up the good work :) .

  2. Pedro's Gravatar Pedro
    July 20, 2011 at 11:15 am | Permalink

    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

  3. Jax's Gravatar Jax
    February 14, 2011 at 4:39 pm | Permalink

    I’ve been hunting for hours for a simple solution like this, works a treat thanks! I wonder what the performance overheads are like?

  4. J²'s Gravatar J²
    October 13, 2009 at 3:25 pm | Permalink

    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.

  5. SingingEels.com's Gravatar SingingEels.com
    March 11, 2009 at 12:26 pm | Permalink

    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)

Leave a Reply

*
CraigWardman.com
Car Leasing | Lease Cars