c# – LINQ’s Distinct() on a particular property

EDIT: This is now part of MoreLINQ.
What you need is a “distinct-by” effectively. I don’t believe it’s part of LINQ as it stands, although it’s fairly easy to write:

public static class EnumerableExtensions
{
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;
}
}
}
}

Source: c# – LINQ’s Distinct() on a particular property – Stack Overflow

Leave a Reply

Your email address will not be published. Required fields are marked *