2009-05-04 25 views
12

私はItemID(int)とScore(int)プロパティを持つHitという名前の(C#)クラスを持っています。私はそれを省略するために、残りの詳細をスキップします。今度は自分のコードで、私は次の選択を(新しいリストに)行う必要がある巨大なListを持っています:スコアごとに並べられた個々のHit.ItemIDのすべてのHit.Scoreの合計を取得する必要があります。私は元のリストで、次の項目SUMとORDER BYのLinqクエリ

ItemID=3, Score=5 
ItemID=1, Score=5 
ItemID=2, Score=5 
ItemID=3, Score=1 
ItemID=1, Score=8 
ItemID=2, Score=10 

を持っているのであれば結果の一覧には、次のものが含まれている必要があります

ItemID=2, Score=15 
ItemID=1, Score=13 
ItemID=3, Score=6 

誰かが助けることができますか?

答えて

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