我有这个
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使用的是匿名类型,因此没有与之关联的类型。
“帮帮我,欧比·万·克诺比,你是我唯一的希望”
发布于 2009-07-01 22:17:20
诀窍是创建一个仅适用于推断类型的比较器。例如:
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);
发布于 2009-08-06 14:56:44
大多数情况下,当您进行比较(为了相等或排序)时,您感兴趣的是选择要进行比较的键,而不是相等或比较方法本身(这是Python的列表排序API背后的思想)。
这里有一个键相等比较器here的例子。
发布于 2011-06-01 00:19:25
我注意到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>
。
https://stackoverflow.com/questions/1071609
复制相似问题