Advertisement
Guest User

Untitled

a guest
Apr 24th, 2014
37
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.46 KB | None | 0 0
  1. public static IEnumerable<T> Distinct<T, TKey>(this IEnumerable<T> items, Func<T, TKey> keySelector, IEqualityComparer<TKey> comparer)
  2. {
  3. return items.Distinct(new KeyEqualityComparer<T, TKey>(keySelector, comparer.Equals));
  4. }
  5.  
  6. class KeyEqualityComparer<T, TResult>: IEqualityComparer<T>
  7. {
  8. private readonly Func<T, TResult> _KeySelector;
  9. private readonly Func<TResult, TResult, bool> _Predicate;
  10.  
  11. public KeyEqualityComparer(Func<T, TResult> keySelector, Func<TResult, TResult, bool> predicate)
  12. {
  13. if (keySelector == null)
  14. throw new ArgumentNullException("keySelector");
  15. _KeySelector = keySelector;
  16. _Predicate = predicate ?? System.Collections.Generic.EqualityComparer<TResult>.Default.Equals;
  17. }
  18.  
  19. public bool Equals(T x, T y)
  20. {
  21. return _Predicate(_KeySelector(x), _KeySelector(y));
  22. }
  23.  
  24. public int GetHashCode(T obj)
  25. {
  26. // Always return the same value to force the call to IEqualityComparer<T>.Equals
  27. return 0;
  28. }
  29. }
  30.  
  31. // TODO: Use C# 6 primary constructor and read-only autoprops :)
  32. public class Person
  33. {
  34. public string Name { get; set; }
  35. public string Hobby { get; set; }
  36. public string Profession { get; set; }
  37. }
  38.  
  39. var people = new List<Person>
  40. {
  41. new Person { Name="Tom", Hobby="Minecraft", Profession = "Student" },
  42. new Person { Name="Robin", Hobby="Taunting", Profession = "Outlaw" },
  43. new Person { Name="Robin", Hobby="Angry Birds", Profession = "Student" },
  44. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement