c# - 使用 linq 返回对象列表,其中属性总和是列表列表中的 Max()
问题描述
我有一个对象列表(List<List<Product>>
)。我只想返回一个列表列表,其中内部列表中sum
的cost
最高。
我试图在 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();
我想从条件成立的可用列表中返回一个列表。附加的代码返回空值。
谢谢
解决方案
如果我对您的理解正确,您正在寻找ArgMax
(Argument 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)
推荐阅读
- dataframe - 尝试按熊猫数据框分组并获取其中一列具有最大值的行时出现值错误
- node.js - Nodejs mqtt 客户端无法连接到配置有可信 CA 的 mosquitto 代理
- rdf - 一般问题:使用 wikidata 和 RDF
- version-control - Perforce:如何将稍后的提交应用于同步到早期版本的工作区?
- java - 创建新的 libgdx 项目时如何解决此“Launching Box2DBuild”错误?
- qt - DirectShowPlayerService::doRender: 未解决的错误代码 0x80040266(IDispatch 错误 #102)
- docker - 不可删除或持久的 docker-compose 卷或数据存储
- c# - 如何更改父视图模型的属性
- youtube-analytics-api - 通过内容管理器帐户的客户端 ID 访问 youtube 分析 API
- django - 模板中foreginKey的Django问题