gpt4 book ai didi

c# - LINQ 查询到 Group 并获得 Sum

转载 作者:太空宇宙 更新时间:2023-11-03 22:59:47 25 4
gpt4 key购买 nike

我有以下查询,它加入了由 StationId 加入的 RailwayStation 对象和 ExpenditureData 对象的集合,我正在尝试获取前 10 个 StationCargoCodes(Station 对象的一个​​属性),并选择顶部的 ExpenditureCost 的总和10 但我无法获得正确的语法:

var data = (from s in stations join e in expenditureData on s.stationId 
equals e.StationId
orderby e.expenditureAmount descending
select s)
.Sum(e => e.expenditureAmount)
.GroupBy(n => n.StationCargoCode)
.Take(10);

为此,我需要什么 LINQ 来进行分组和求和?

最佳答案

var query = from s in stations
join e in expenditureData
on s.stationId equals e.StationId into se
group se by new
{
s.StationCargoCode, ExpenditureCostSum = se.Sum(x => x.ExpenditureCost)
} into g
orderby g.Key.ExpenditureCostSum descending
select g.Key;

var top10 = query.Take(10).ToList();

关于c# - LINQ 查询到 Group 并获得 Sum,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43621878/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com