c# – 告诉LINQ区分要返回的项目
作者:互联网
我理解如何在IEnumerable上做一个Distinct()并且我必须为更高级的东西创建一个IEqualityComparer,但是有没有一种方法可以告诉哪个重复的项目要返回?
例如,假设你有一个List< T>
List<MyClass> test = new List<MyClass>();
test.Add(new MyClass {ID = 1, InnerID = 4});
test.Add(new MyClass {ID = 2, InnerID = 4});
test.Add(new MyClass {ID = 3, InnerID = 14});
test.Add(new MyClass {ID = 4, InnerID = 14});
然后你做:
var distinctItems = test.Distinct(new DistinctItemComparer());
class DistinctItemComparer : IEqualityComparer<MyClass> {
public bool Equals(MyClass x, MyClass y) {
return x.InnerID == y.InnerID;;
}
public int GetHashCode(MyClassobj) {
return obj.InnerID.GetHasCode();
}
}
此代码将返回ID为1和3的类.有没有办法返回ID匹配2& 4.
解决方法:
您不希望区别 – 您希望根据ID对项目进行分组并为它们选择“最大”元素:
var distinctItems = test.Distinct(new DistinctItemComparer());
var otherItems = test.GroupBy(a => a.InnerID, (innerID, values) => values.OrderBy(b => b.ID).Last());
var l1 = distinctItems.ToList();
var l2 = otherItems.ToList();
l1 =您当前的列表
l2 =您想要的清单
标签:c,linq,net-3-5,ienumerable,c-3-0 来源: https://codeday.me/bug/20190715/1472658.html