我有这个
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,但由于我使用的是匿名类型,因此没有与之关联的类型。
“帮助我Obi Wan Kenobi,你是我唯一的希望”
答案 0 :(得分:18)
诀窍是创建一个仅适用于推断类型的比较器。例如:
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);
答案 1 :(得分:3)
大多数时候你比较(对于相等或排序)你有兴趣选择要比较的键,而不是相等或比较方法本身(这是Python的列表排序API背后的想法)。
有一个密钥相等比较器here的示例。
答案 2 :(得分:1)
我注意到JaredPar的答案并没有完全回答这个问题,因为像Distinct和Except这样的设置方法需要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>
来选择哈希码。