我有一份记录清单,即
Id, Activity, Marks
1, A, 12
1, B, 14
1, B, 15
2, A, 1
2,A,100
我想按Id和Activity对记录进行分组,然后返回记录的总和。
如何使用LINQ实现这一目标?例如。结果应该是:
Id, Activity, TotalMarks
1, A, 12
1, B, 29
2, A, 101
答案 0 :(得分:5)
List<Activity> activity;
activity
.GroupBy (a => new {a.Id, a.Activity})
.Select (ag => new {ag.Key.Id, ag.Key.Activity, TotalMarks=ag.Select(a => a.Marks).Sum()})
答案 1 :(得分:0)
var result =
(from x in values
group x by new {x.Id, x.Activity} into g
select new MyClass()
{
Id = g.Key.Id,
Activity = g.Key.Activity,
TotalMarks = g.Sum(y => y.Marks)
}).ToList();
其中MyClass
具有指定的属性。