Created
November 26, 2013 11:44
-
-
Save feanz/7657096 to your computer and use it in GitHub Desktop.
DistinctBy Linq Expression
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <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