Linq Query with SUM and ORDER BY(使用 SUM 和 ORDER BY 进行 Linq 查询)
问题描述
我有一个名为 Hit 的 (C#) 类,它具有 ItemID (int) 和 Score (int) 属性.我跳过其余的细节以保持简短.现在在我的代码中,我有一个巨大的列表,我需要在该列表上执行以下选择(进入一个新列表):我需要为每个单独的 Hit.ItemID 获取所有 Hit.Score 的总和,按分数排序.所以如果我在原始列表中有以下项目
I have a (C#) class called Hit with an ItemID (int) and a Score (int) property. I skip the rest of the details to keep it short. Now in my code, I have a huge List on which I need to do the following select (into a new List): I need to get the sum of all Hit.Score's for each individual Hit.ItemID, ordered by Score. So if I have the following items in the original list
ItemID=3, Score=5
ItemID=1, Score=5
ItemID=2, Score=5
ItemID=3, Score=1
ItemID=1, Score=8
ItemID=2, Score=10
结果列表应包含以下内容:
the resulting List should contain the following:
ItemID=2, Score=15
ItemID=1, Score=13
ItemID=3, Score=6
有人可以帮忙吗?
推荐答案
var q = (from h in hits
group h by new { h.ItemID } into hh
select new {
hh.Key.ItemID,
Score = hh.Sum(s => s.Score)
}).OrderByDescending(i => i.Score);
这篇关于使用 SUM 和 ORDER BY 进行 Linq 查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 SUM 和 ORDER BY 进行 Linq 查询


基础教程推荐
- 重新排序 WPF TabControl 中的选项卡 2022-01-01
- SonarQube C# 分析失败“不是指针的有效行偏移" 2022-01-01
- 获取C#保存对话框的文件路径 2022-01-01
- C# 9 新特性——record的相关总结 2023-04-03
- 如果条件可以为空 2022-01-01
- Mono https webrequest 失败并显示“身份验证或解密失败" 2022-01-01
- 更新 Visual Studio 中的 DataSet 结构以匹配新的 SQL 数据库结构 2022-01-01
- 从 C# 控制相机设备 2022-01-01
- 在 VB6 或经典 ASP 中使用 .NET 2022-01-01
- 将数据集转换为列表 2022-01-01