I have a list of records i.e.
Id, Activity, Marks
1, A, 12
1, B, 14
1, B, 15
2, A, 1
2,A,100
I want to group the records by Id and Activity and then return the sum of the records.
How do I achieve that using LINQ? E.g. result should be:
Id, Activi开发者_运维百科ty, TotalMarks
1, A, 12
1, B, 29
2, A, 101
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()})
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();
Where MyClass
has the properties specified.
精彩评论