문제
나는 itemid (int)와 score (int) 속성으로 hit이라는 (c#) 클래스가 있습니다. 나는 나머지 세부 사항을 건너 뛰고 짧게 유지합니다. 이제 내 코드에는 다음과 같은 선택을 해야하는 거대한 목록이 있습니다 (새 목록에) : 각 Hit.score 's에 대한 합계를 가져와야합니다. 그래서 원래 목록에 다음 항목이 있다면
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