3

I have the following value in a list by

Feb 13  100 
Feb 13  150 
Feb 13  127 
Feb 14  50

using linq how do I return another list with the sum for each date including the previous days total?

e.g

Feb 13 357  (Sum of Feb 13)   
Feb 14 407  (Sum of Feb 14 + Sum of Feb 13)

with some mucking about

list= list.OrderBy(i => i.date)
                    .Distinct().Select(
                i =>
                    {
                        np+= i.rh;
                        nh+= i.hm;
                        return new Po
                            {
                                date= i.date,
                                NH =  nh,

                            };
                    }).ToList();

this return this list:

Feb 13  100 
Feb 13  250 
Feb 13  377 
Feb 14  427

I would like just

 Feb 13 357  
 Feb 14 407 
Fabii
  • 3,820
  • 14
  • 51
  • 92

3 Answers3

3
decimal runningTotal = 0;
var result = from item in items
             orderby item.Date
             group items by item.Date into grp
             let sum = items.Where(x => x.Date == grp.Key).Sum(x => x.Amount)
             select new
             {
                 Date = grp.Key,
                 Sum = runningTotal += sum,
             };
david.s
  • 11,283
  • 6
  • 50
  • 82
0

you can try something like this if you know the values ahead

   var Total = listval.Sum(od => od.vall)+listval.where(od => od.date=="Feb 13").Sum(od =>
 od.vall)+listval.where(od => od.date=="Feb 14").Sum(od => od.vall);
COLD TOLD
  • 13,513
  • 3
  • 35
  • 52
0

You can do so by grouping the objects and using the Sum within the group. The link Mark posted shows exactly how to do that.

Mathieson
  • 1,698
  • 2
  • 17
  • 19