我有此

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

我想如果它这样做允许在那里

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

我试图使用通用 LambdaComparer 但由于使用im匿名类型没有类型它与相关联。

“帮我欧比旺·克诺比,你是我唯一的希望”

有帮助吗?

解决方案

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

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

现在我可以做以下...哈克溶液:

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