Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Person1: Id=1, Name="Test1"
- Person2: Id=1, Name="Test1"
- Person3: Id=2, Name="Test2"
- 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;
- }
- }
- }
- List<Person> distinctPeople = allPeople
- .GroupBy(p => p.PersonId)
- .Select(g => g.First())
- .ToList();
- List<Person> distinctPeople = allPeople
- .GroupBy(p => new {p.PersonId, p.FavoriteColor} )
- .Select(g => g.First())
- .ToList();
- people.Where(p => !people.Any(q => (p != q && p.Id == q.Id)));
- var people = new List<Person>();
- people.Add(new Person(1, "a", "b"));
- people.Add(new Person(2, "c", "d"));
- people.Add(new Person(1, "a", "b"));
- foreach (var person in people.Distinct(p => p.ID))
- // do stuff with unique list here.
Add Comment
Please, Sign In to add comment