Created
August 15, 2017 12:13
-
-
Save dejanstojanovic/ac38f7f0f5e07854dc3a656e5cafff97 to your computer and use it in GitHub Desktop.
Distinct by a specific object property in LINQ
This file contains hidden or 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
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