linqlambdaanonymous-typesiequalitycomparer

IEqualityComparer for anonymous type


I have this

 var n = ItemList.Select(s => new { s.Vchr, s.Id, s.Ctr, s.Vendor, s.Description, s.Invoice }).ToList();
 n.AddRange(OtherList.Select(s => new { s.Vchr, s.Id, s.Ctr, s.Vendor, s.Description, s.Invoice }).ToList(););
 

I would like to do this if it where allowed

n = n.Distinct((x, y) => x.Vchr == y.Vchr)).ToList();

I tried using the generic LambdaComparer but since im using anonymous types there is no type associate it with.

"Help me Obi Wan Kenobi, you're my only hope"


Solution

  • The trick is to create a comparer that only works on inferred types. For instance:

    public class Comparer<T> : IComparer<T> {
      private Func<T,T,int> _func;
      public Comparer(Func<T,T,int> func) {
        _func = func;
      }
      public int Compare(T x,  T y ) {
        return _func(x,y);
      }
    }
    
    public static class Comparer {
      public static Comparer<T> Create<T>(Func<T,T,int> func){ 
        return new Comparer<T>(func);
      }
      public static Comparer<T> CreateComparerForElements<T>(this IEnumerable<T> enumerable, Func<T,T,int> func) {
        return new Comparer<T>(func);
      }
    }
    

    Now I can do the following ... hacky solution:

    var comp = n.CreateComparerForElements((x, y) => x.Vchr == y.Vchr);