C# – Linq Distinct on a particular Property

Updated on     Kisan Patel


How to use Distinct when I do not have a simple list (a simple list of integers is pretty easy to do, this is not the question). What if want to use Distinct on a list of an Object on ONE or MORE Properties of the object?


Method 1: MoreLinq has a DictinctBy method that you can use:

It will allow you to do:

public static IEnumerable<TSource> DistinctBy<TSource, TKey>
            (this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
      HashSet<TKey> seenKeys = new HashSet<TKey>();
      foreach (TSource element in source)
         if (seenKeys.Add(keySelector(element)))
             yield return element;

So to find the distinct values using just the Id property, you could use:

var query = people.DistinctBy(p => p.Id);

And to use multiple properties, you can use anonymous types, which implement equality appropriately:

var query = people.DistinctBy(p => new { p.Id, p.Name });

Method 2:

Try this:

var query = people.GroupBy(x => x.Text).Select(x => x.First());

This will group the table by Text and use the first row from each groups resulting in rows where Text is distinct.

C# Entity Framework LINQ

Leave a Reply