Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq Query with SUM and ORDER BY

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?

like image 271
Mats Avatar asked May 04 '09 15:05

Mats


1 Answers

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);
like image 67
user95144 Avatar answered Sep 21 '22 06:09

user95144