C# 使用 SUM 和 ORDER BY 的 Linq 查询

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/820552/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-05 02:29:10  来源:igfitidea点击:

Linq Query with SUM and ORDER BY

c#linqsumsql-order-by

提问by Mats

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

我有一个名为 Hit 的 (C#) 类,带有一个 ItemID (int) 和一个 Score (int) 属性。我跳过其余的细节以保持简短。现在在我的代码中,我有一个巨大的列表,我需要在上面执行以下选择(到一个新列表中):我需要获取每个单独的 Hit.ItemID 的所有 Hit.Score 的总和,按分数排序。所以如果我在原始列表中有以下项目

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

Can somebody help?

有人可以帮忙吗?

采纳答案by user95144

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);

回答by Daniel Brückner

IEnumerable<Hit> result = hits.
   GroupBy(hit => hit.ItemID).
   Select(group => new Hit 
                   {
                      ItemID = group.Key,
                      Score = group.Sum(hit => hit.Score)
                   }).
   OrderByDescending(hit => hit.Score);