开发者

How do I use Linq Sum After grouping by

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜