我有我的物品列表:
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", Price = 20, OtherData = "Z2" },
new MyObj { Title = "AAA", Price = 30, OtherData = "Z5" },
new MyObj { Title = "BBB", Price = 10, OtherData = "Z10" },
new MyObj { Title = "CCC", Price = 99, OtherData = "ZZ" }
};
获取具有唯一标题和最大(价格)列表的最佳方式是什么。 结果列表必须是:
var ret = new List<MyObj> {
new MyObj { Title = "BBB", Price = 20, OtherData = "Z2" },
new MyObj { Title = "AAA", Price = 30, OtherData = "Z5" },
new MyObj { Title = "CCC", Price = 99, 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(不能使用语句 lambda),您可以使用:
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));
var ret = list.GroupBy(x => x.Title)
.Select(g => g.Aggregate((a, x) => (x.Price > a.Price) ? x : a));
(如果您需要结果是
List<T>
而不是 IEnumerable<T>
序列,那么只需将 ToList
调用标记到末尾即可。)
var ret = list.OrderByDescending(x => x.Price).GroupBy(x => x.Title).Select(@group => @group.ElementAt(0)).ToList();
这应该可以。
想提一下
var query = list.GroupBy(x => x.Title)
.Select(group => group.Where(x => x.Price == group.Max(y => y.Price))
.First());
应该是
var query = list.GroupBy(x => x.Title)
.First(group => group.Where(x => x.Price == group.Max(y => y.Price)));
我喜欢 Richard 解决“每组最大 n 个”问题的方法。
var query = list
.OrderByDescending(o => o.Price) //set ordering
.GroupBy(o => o.Title) //set group by
.Select(o => o.First()); //take the max element
但是需要稍微修改一下
var query = list
.OrderByDescending(o => o.Price) //set ordering
.GroupBy(o => o.Title) //set group by
.Select(o => o.Where(k => k.Price == o.First().Price)) //take max elements
会让事情变得简单。
var list = list.GroupBy(g => g.Title)
.Select(s =>
{
return s.MaxBy(x => x.Price);
}).ToList();