Skip to content

Instantly share code, notes, and snippets.

@dejanstojanovic
Created August 15, 2017 12:13
Show Gist options
  • Save dejanstojanovic/ac38f7f0f5e07854dc3a656e5cafff97 to your computer and use it in GitHub Desktop.
Save dejanstojanovic/ac38f7f0f5e07854dc3a656e5cafff97 to your computer and use it in GitHub Desktop.
Distinct by a specific object property in LINQ
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;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment