Skip to content

Instantly share code, notes, and snippets.

@uzbekdev1
Last active July 24, 2021 10:22
Show Gist options
  • Save uzbekdev1/30f2036f5a5364f76f483632d2922eca to your computer and use it in GitHub Desktop.
Save uzbekdev1/30f2036f5a5364f76f483632d2922eca to your computer and use it in GitHub Desktop.
LINQ - DistinctBy
var query = people.DistinctBy(p => p.Id);
var query = people.DistinctBy(p => new { p.Id, p.Name });
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