Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Summing similar values with a list using Linq [duplicate]

Tags:

c#

linq

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 
like image 827
Fabii Avatar asked Dec 06 '25 08:12

Fabii


1 Answers

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,
             };
like image 136
david.s Avatar answered Dec 07 '25 21:12

david.s



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!