Thursday, May 5, 2011

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?

From stackoverflow
  • 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);
    
  • 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);
    

0 comments:

Post a Comment