我有一个我的对象列表:
class MyObj { public String Title { get; set; } public Decimal Price { get; set; } public String OtherData { get; set; } } var list = new List<MyObj> { new MyObj { Title = "AAA",Price = 20,OtherData = "Z1" },new MyObj { Title = "BBB",OtherData = "Z2" },new MyObj { Title = "AAA",Price = 30,OtherData = "Z5" },Price = 10,OtherData = "Z10" },new MyObj { Title = "CCC",Price = 99,OtherData = "ZZ" } };
获得具有唯一Title和MAX(价格)的列表的最佳方法是什么.
结果列表需要是:
var ret = new List<MyObj> { new MyObj { Title = "BBB",OtherData = "ZZ" } };
解决方法
好吧,你可以这样做:
var query = list.GroupBy(x => x.Title) .Select(group => { decimal maxPrice = group.Max(x => x.Price); return group.Where(x => x.Price == maxPrice) .First(); };
如果你需要LINQ to sql(你不能使用语句lambdas),你可以使用:
var query = list.GroupBy(x => x.Title) .Select(group => group.Where(x => x.Price == group.Max(y => y.Price)) .First());
请注意,在LINQ to Objects中,效率会低于Where的每次迭代,它会重新计算最高价格.
如果您希望能够返回具有给定名称的多个项目(如果它们具有相同的价格),请调整.First()部分.
在LINQ to Objects中,您还可以使用MoreLINQ的MaxBy
方法:
var query = list.GroupBy(x => x.Title) .Select(group => group.MaxBy(x => x.Price));