使用 SUM 和 ORDER BY 进行 Linq 查询 [英] Linq Query with SUM and ORDER BY

查看:33
本文介绍了使用 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 查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆