code_junkie

Linq Distinct on a particular Property

Nov 13th, 2011
163
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.96 KB | None | 0 0
  1. Person1: Id=1, Name="Test1"
  2. Person2: Id=1, Name="Test1"
  3. Person3: Id=2, Name="Test2"
  4.  
  5. public static IEnumerable<TSource> DistinctBy<TSource, TKey>
  6. (this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
  7. {
  8. HashSet<TKey> seenKeys = new HashSet<TKey>();
  9. foreach (TSource element in source)
  10. {
  11. if (seenKeys.Add(keySelector(element)))
  12. {
  13. yield return element;
  14. }
  15. }
  16. }
  17.  
  18. List<Person> distinctPeople = allPeople
  19. .GroupBy(p => p.PersonId)
  20. .Select(g => g.First())
  21. .ToList();
  22.  
  23. List<Person> distinctPeople = allPeople
  24. .GroupBy(p => new {p.PersonId, p.FavoriteColor} )
  25. .Select(g => g.First())
  26. .ToList();
  27.  
  28. people.Where(p => !people.Any(q => (p != q && p.Id == q.Id)));
  29.  
  30. var people = new List<Person>();
  31.  
  32. people.Add(new Person(1, "a", "b"));
  33. people.Add(new Person(2, "c", "d"));
  34. people.Add(new Person(1, "a", "b"));
  35.  
  36. foreach (var person in people.Distinct(p => p.ID))
  37. // do stuff with unique list here.
Add Comment
Please, Sign In to add comment