Advertisement
GeneralGDA

Distinct for collection of objects of anonymus types.

Dec 5th, 2015
481
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.52 KB | None | 0 0
  1. internal sealed class DelegatingComparer<TSource, TField> : IEqualityComparer<TSource> where TField : class
  2. {
  3.     private readonly Func<TSource, TField> _getField;
  4.  
  5.     internal DelegatingComparer(Func<TSource, TField> getField)
  6.     {
  7.         if (null == getField)
  8.         {
  9.             throw new ArgumentNullException("getField");
  10.         }
  11.  
  12.         _getField = getField;
  13.     }
  14.  
  15.     public bool Equals(TSource x, TSource y)
  16.     {
  17.         var a = _getField(x);
  18.         var b = _getField(y);
  19.  
  20.         if (null == a)
  21.         {
  22.             return null == b;
  23.         }
  24.  
  25.         return a.Equals(b);
  26.     }
  27.  
  28.     public int GetHashCode(TSource @object)
  29.     {
  30.         var fieldValue = _getField(@object);
  31.         return null == fieldValue ? 0 : fieldValue.GetHashCode();
  32.     }
  33. }
  34.  
  35. internal static class DelegatingExtensions
  36. {
  37.     internal static IEnumerable<T> MyDistinct<T, TField>(this IEnumerable<T> source, Func<T, TField> getField) where TField : class
  38.     {
  39.         if (null == source)
  40.         {
  41.             throw new ArgumentNullException("source");
  42.         }
  43.  
  44.         if (null == getField)
  45.         {
  46.             throw new ArgumentNullException("getField");
  47.         }
  48.  
  49.         return source.Distinct(new DelegatingComparer<T, TField>(getField));
  50.     }
  51. }
  52.  
  53. //usage
  54.  
  55. var names = new [] { "Петя", "Вася", "Вася", "Коля", "Пахом" };
  56. var original = names.Select(n => new { Name = n, n.Length }); // how to call Enumerable.Distinct?
  57.  
  58. var filtered = original.MyDistinct(v => v.Name);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement