kjg*_*lla 33 linq lambda anonymous-types 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(););
Run Code Online (Sandbox Code Playgroud)
如果允许,我想这样做
n = n.Distinct((x, y) => x.Vchr == y.Vchr)).ToList();
Run Code Online (Sandbox Code Playgroud)
我尝试使用通用的LambdaComparer,但由于我使用的是匿名类型,因此没有类型与之关联.
"帮助我Obi Wan Kenobi,你是我唯一的希望"
Jar*_*Par 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);
}
}
Run Code Online (Sandbox Code Playgroud)
现在我可以做以下...... hacky解决方案:
var comp = n.CreateComparerForElements((x, y) => x.Vchr == y.Vchr);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10011 次 |
| 最近记录: |