SUMおよびORDER BYを使用したLinqクエリ
-
03-07-2019 - |
質問
ItemID(int)およびScore(int)プロパティを持つHitという(C#)クラスがあります。残りの詳細を省略して、短くします。これで、コードに次の選択(新しいリスト)を実行する必要がある巨大なリストがあります:スコア順に並べられた個々のHit.ItemIDのすべてのHit.Scoreの合計を取得する必要があります。元のリストに次のアイテムがある場合
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
誰か助けてもらえますか?
解決
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);
所属していません StackOverflow