开发者

How do I use Linq Sum After grouping by

开发者 https://www.devze.com 2023-03-17 07:00 出处:网络
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.

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

精彩评论

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