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

  • Robert Bratton February 14, 2020   Reply →

    There are minor problems with the code above. Here’s my version:

    using System;
    using System.Collections.Generic;
    using System.Linq;

    namespace Upmc.PersonSimulator.Domain.Business.Extensions
    {
    public static class EnumerableExtensions
    {
    public static IEnumerable DistinctBy(this IEnumerable list, Func propertySelector)
    {
    return list
    .GroupBy(propertySelector)
    .Select(x => x.First());
    }
    }
    }

Leave a comment