匿名类型的 IEqualityComparer [英] IEqualityComparer for anonymous type
本文介绍了匿名类型的 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.
帮助我欧比旺克诺比,你是我唯一的希望"
"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屋!
查看全文