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

标签 c# linq

我有以下查询,它加入了由 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/

相关文章:

c# - Entity Framework 在没有标识列的表上不起作用

c# - 使用 C# 和 Linq 创建一个包含来自两个输入数组的唯一项的数组

c# - 我可以用 LINQ 做到这一点吗?

c# - linq mysql 查询 int 数组

c# - Resharper 使用扩展方法将 foreach 转换为 LINQ

c# - 如何在 MVC 中实现所有 sql 表的搜索功能?

c# - 如何在 XML 文件中的特定部分之后添加一个部分,c#

c# - 如何使用 Entity Framework 将外键设置为主键?

c# - 在 LINQ 中使用命名元组数组

c# - Linq GroupBy 和 Passed Where 谓词