匿名类型的IEqualityComparer

匿名类型的IEqualityComparer

问题描述:

我有这个

 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();

我尝试使用通用的 LambdaComparer ,但是由于我使用的是匿名类型,因此没有类型与之关联.

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

请帮我Obi Wan Kenobi,您是我唯一的希望"

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

诀窍是创建一个仅适用于推断类型的比较器.例如:

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);
  }
}

现在我可以执行以下... hacky解决方案:

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

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