Skip to content

Instantly share code, notes, and snippets.

@yang-qu
Last active August 29, 2015 14:01
Show Gist options
  • Select an option

  • Save yang-qu/c25f60371f1219855449 to your computer and use it in GitHub Desktop.

Select an option

Save yang-qu/c25f60371f1219855449 to your computer and use it in GitHub Desktop.
LINQ DistinctBy
using System;
using System.Collections.Generic;
using System.Linq;
public static class LINQExtension
{
public static IEnumerable<TSource> DistinctBy<TSource, TKey>
(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
{
HashSet<TKey> knownKeys = new HashSet<TKey>();
foreach (TSource element in source)
{
if (knownKeys.Add(keySelector(element)))
{
yield return element;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment