IEqualityComparer 用于匿名类型

问题描述 投票:0回答:3

我有这个

 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 但由于我使用匿名类型,因此没有与之关联的类型。

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

linq lambda anonymous-types iequalitycomparer
3个回答
19
投票

技巧是创建一个仅适用于推断类型的比较器。例如:

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解决方案:

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

3
投票

大多数时候,当您进行比较(相等或排序)时,您感兴趣的是选择要比较的键,而不是相等或比较方法本身(这是 Python 列表排序 API 背后的想法)。

这里有一个示例键相等比较器


1
投票
我注意到 JaredPar 的答案并没有完全回答问题,因为像 Distinct 和 except 这样的 set 方法需要

IEqualityComparer<T>

 而不是 
IComparer<T>
。下面假设 IEquatable 将有一个合适的 GetHashCode,并且它当然有一个合适的 Equals 方法。

public class GeneralComparer<T, TEquatable> : IEqualityComparer<T> { private readonly Func<T, IEquatable<TEquatable>> equatableSelector; public GeneralComparer(Func<T, IEquatable<TEquatable>> equatableSelector) { this.equatableSelector = equatableSelector; } public bool Equals(T x, T y) { return equatableSelector.Invoke(x).Equals(equatableSelector.Invoke(y)); } public int GetHashCode(T x) { return equatableSelector(x).GetHashCode(); } } public static class GeneralComparer { public static GeneralComparer<T, TEquatable> Create<T, TEquatable>(Func<T, TEquatable> equatableSelector) { return new GeneralComparer<T, TEquatable>(equatableSelector); } }

与 JaredPar 的答案中使用的静态类技巧相同的推论。

更一般地说,您可以提供两个

Func

:一个 
Func<T, T, bool>
 用于检查相等性,
Func<T, T, int>
 用于选择哈希码。

© www.soinside.com 2019 - 2024. All rights reserved.