Linq Query with SUM and ORDER BY

狂风中的少年 提交于 2019-12-18 14:56:39

问题


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?


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/820552/linq-query-with-sum-and-order-by

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!