C#LINQ:获取最高价商品

| 我有一个对象列表:
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\" }
};
获得具有唯一标题和MAX(Price)的列表的最佳方法是什么。 结果列表必须为:
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(不能使用语句lambdas),则可以使用:
var query = list.GroupBy(x => x.Title)
       .Select(group => group.Where(x => x.Price == group.Max(y => y.Price))
                             .First());
注意,在LINQ to Objects中效率不如iteration4ѭ的每次迭代中那样,它将重新计算最高价格。 如果您希望能够退回多个具有给定名称的商品(如果它们的价格相同),请调整“ 5”部分。 在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));
(如果您需要结果是results9ѭ而不是
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)));
我喜欢针对每组最多n个问题的Richard解决方案。
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
    

要回复问题请先登录注册