LINQ DistinctBy - With Lambda Expression Parameter

A useful extension method that c# .NET provides is Distinct(). Sometimes you need to get distinct objects by a property of those objects, however, and there is no overload of Distinct() that accepts a lambda expression. Luckily, it’s easy enough to create our own.

A custom DistinctBy extension method can actually be quite simple.

public static IEnumerable DistinctBy(this IEnumerable list, Func<t, object> propertySelector)
   return list.GroupBy(propertySelector).Select(x => x.First());

An example usage:

var list = new List
   new { Id = 1, Property = "value1" },
   new { Id = 2, Property = "value2" },
   new { Id = 3, Property = "value1" }

// returns objects with Id = 1, 2, but not 3
var distinctList = list.DistinctBy(x => x.Property);

Alternatively you can check out morelinq, a library full of extensions to LINQ to Objects, including a DistinctBy implementation.

You may also like

One comment

  • complement December 31, 2017   Reply →

    Hey theгe just wanted to give you a quick heads up. The text in your
    artiсle seem to bе running off the screen in Safari.
    I’m not sure іf this is a format iѕsue or something to do with
    internet browser compatibility but I figured I’d ρost to let you
    know. The design and style look great though!

    Hope you get thе problem resolved ѕoon. Ϲheers

Leave a comment