首页 > 解决方案 > 使用 linq 返回对象列表,其中属性总和是列表列表中的 Max()

问题描述

我有一个对象列表(List<List<Product>>)。我只想返回一个列表列表,其中内部列表中sumcost最高。

我试图在 C# 中使用 linq 查询来实现这一点。不过,我对这些 linq 查询不太熟悉。

List<List<Product>> query = (from lists in ListOfList
                            where lists.Sum(x => x.factor) <= 10
                            orderby lists.Sum(x => x.cost) descending
                            select lists).ToList();

List<Product> tempList = query.FirstOrDefault();

我想从条件成立的可用列表中返回一个列表。附加的代码返回空值。

谢谢

标签: c#listlinq

解决方案


如果我对您的理解正确,您正在寻找ArgMaxArgument such that collection 达到其最大值), 标准 Linq不提供这种方法,但可以在以下帮助下进行模拟Aggregate

List<List<Product>> data = ...

List<Product> result = data
  .Select(list => new {
     list,                                    // list
     max = list
       .Where(product => product.Factor < 10) 
       .Sum(product => product.cost)          // with criterium to maximize
   })
  .Aggregate((s, a) => s.max > a.max ? s : a) // ArgMax implementation
  .list;                                      // We want list only (without max) 

推荐阅读