我有一个名为Hit的(C#)类,它带有ItemID(int)和Score(int)属性。我跳过其余的细节以保持简短。现在在我的代码中,我有一个巨大的List,我需要做以下select(进入一个新的List):我需要获得每个Hit.ItemID的所有Hit.Score的总和,按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);
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top