Search code examples
c#asp.net-mvcdatabasesum

How to obtain a column total for values in a list - double of anonymous type


I have a database that contains a column of filtered double values that I am trying to get the total of. I have no problem building a collection of values but can't calculate the value combined total.

My Query

var query2 = from r in db.Clocks
where r.WkNo == Current_Wk
group r by r.DailyHrs into g
select new
{
Value = g.Sum( item => item.DailyHrs)                  
};
var MyList = (query2.ToList());

//The resulting list
//Value = 0.00
//Value = 9.25
//Value = 8.00

How can I determine the total value? i.e 0.00 + 9.25 + 8.00

I have looked at many posts here but can't get it to work.


Solution

  • "firstly materialize the query with .ToList() before calling .Sum():" [Reference] https://stackoverflow.com/a/20338921/8049376

    var query2 = (from r in db.Clocks
    where r.WkNo == clock.WkNo
    group r by r.DailyHrs into g
    select new
    {
    Value = g.Sum( item => item.DailyHrs)
    }).ToList();
    
    var sum = query2.Sum(t => t.Value);