LINQ查询用SUM和ORDER BY [英] Linq Query with SUM and ORDER BY

查看:91
本文介绍了LINQ查询用SUM和ORDER BY的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有(C#)类调用与项目编号(int)和一个分数(INT)财产命中。我跳过的细节休息,保持短。现在,在我的代码,我有哪些我需要做下面的选择(进入一个新的列表)一个巨大的列表:我需要得到所有Hit.Score的每一个人Hit.ItemID,按照分值进行排序的总和。所以,如果我有原始列表以下项目

 项ID = 3,分数= 5 
项ID = 1,得分= 5
项ID = 2,分数= 5
项ID = 3,得分= 1
项ID = 1,分数= 8
项ID = 2,得分= 10

结果列表中应包含以下内容:

 项目编号= 2,得分= 15 
项ID = 1,得分= 13
项ID = 3,分数= 6

有人能帮忙吗?


解决方案

  VAR q =(从命中^ h通过新的{} h.ItemID 
H组为HH
选择新{
hh.Key.ItemID,
得分= hh.Sum(S = GT; s.Score)
})OrderByDescending(I => i.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

Can somebody help?

解决方案

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

这篇关于LINQ查询用SUM和ORDER BY的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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