In the below code i have a list i am trying to get values from list using linq query and sum the values.But i don't know how to sum the values.So please help me to resolve the issue.
list contains:
Desc Month level value
M1 Jan L1 2
M1 Jan L2 6
M2 Feb L1 4
M2 Feb L2 1
My Expected Result:
M1 Jan 8
M2 Feb 5
var sums1 = objList
.GroupBy(y => new { y.Desc, y.Month, y.value })
.Select(group => new { KeyValue = group.Key, Count = group.Count() });
You shouldn't be including the value
in your grouping - you want to group by just Desc
and Month
(I assume), then sum the value parts. Two options:
var sums1 = objList
.GroupBy(y => new { y.Desc, y.Month })
.Select(group => new { KeyValue = group.Key, Sum = group.Sum(y => y.value) });
Or in a single call:
var sums1 = objList.GroupBy(
y => new { y.Desc, y.Month },
(key, values) => new { key.Desc, key.Month, Sum = values.Sum(y => y.value) });
See more on this question at Stackoverflow