user609511
user609511

Reputation: 4261

how can i get the sum of Datatable with linq

i m using C# 4.0. my datatable is like this:

ZONE   Value
A      10
A      20
B      5
C      15
C      5

i want to get the sum of Zone.

Zone A = 30
Zone B = 5
Zone C = 20

how can i do that in linq.

Upvotes: 0

Views: 46

Answers (2)

MarcinJuraszek
MarcinJuraszek

Reputation: 125620

var results = (from r in dt.AsEnumerable()
               group r by r.Field<string>("ZONE") into g
               select new {
                   Zone = g.Key,
                   Sum = g.Sum(x => x.Field<int>("Value"))
              })

or

var results = dt.AsEnumerable()
                .GroupBy(
                    x = > x.Field<string>("ZONE"),
                    (k, g) => new { ZONE = k, Sum = g.Sum(x => x.Field<int>("VALUE")) });

Upvotes: 0

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236208

Group rows by value of ZONE field, and then calculate sum of Value fields of all rows in group (grouping key will be zone name):

var query = from r in table.AsEnumerable()
            group r by r.Field<string>("ZONE") into g
            select new {
               Zone = g.Key,
               TotalValue = g.Sum(r => r.Field<int>("Value"))
            };

Upvotes: 1

Related Questions