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 查询


- C# 中多线程网络服务器的模式 2022-01-01
- 输入按键事件处理程序 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- 如何用自己压缩一个 IEnumerable 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01