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