Last active
August 29, 2015 14:01
-
-
Save yang-qu/c25f60371f1219855449 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
| 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