moses
moses

Reputation: 31

To Sum Value using linq

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() });

Upvotes: 1

Views: 1942

Answers (3)

steliosbl
steliosbl

Reputation: 8921

Use LINQ's Sum() extension method for IEnumerable.

  .Select(group => new { KeyValue = group.Key, Sum = group.Sum(obj => obj.value)});

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1503469

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) });

Upvotes: 5

Samvel Petrosov
Samvel Petrosov

Reputation: 7706

Replace your group.Count with group.Sum(x=>x.value)

Upvotes: 1

Related Questions