Skip to content

Instantly share code, notes, and snippets.

@feanz
Created November 26, 2013 11:44
Show Gist options
  • Save feanz/7657096 to your computer and use it in GitHub Desktop.
Save feanz/7657096 to your computer and use it in GitHub Desktop.
DistinctBy Linq Expression
/// <summary>
/// Select distinct elements in collection on a given property
/// </summary>
/// <typeparam name="TSource"></typeparam>
/// <typeparam name="TKey"></typeparam>
/// <param name="source">The collection to filter</param>
/// <param name="keySelector">The property to distinct collection by</param>
/// <returns></returns>
public static IEnumerable<TSource> DistinctBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
{
var seenKeys = new HashSet<TKey>();
return source.Where(element => seenKeys.Add(keySelector(element)));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment