匿名类型的IEqualityComparer [英] IEqualityComparer for anonymous type

查看:170
本文介绍了匿名类型的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);

这篇关于匿名类型的IEqualityComparer的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆