Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to calculate sum of a DataTable's Column in LINQ (to Dataset)?

I'm just started to read up on LINQ and I want to start incorporating it into my code. I know how to compute the sum of a DataTable's column by either "Foreach"-ing through the rows or by doing a compute.sum on the specific column. How do I do the equivalent with LINQ to DataSet?

like image 776
rivera.reyrivera Avatar asked Feb 15 '09 02:02

rivera.reyrivera


2 Answers

If untyped (replace int with the correct data type):

 var sum = table.AsEnumerable().Sum(x=>x.Field<int>(3));

or:

 var sum = table.AsEnumerable().Sum(x=>x.Field<int>("SomeProperty"));

If typed:

 var sum = table.Sum(x=>x.SomeProperty);
like image 50
Marc Gravell Avatar answered Nov 09 '22 11:11

Marc Gravell


If you data field is integer

var sum = TableData.Sum(x => x.FieldName);

If your data field is string then you need to parse it as integer

var sum = TableData.Sum(x => Int32.Parse(x.FieldName));

If your data field is string and you want to store result as string

var sum = TableData.Sum(x => Int32.Parse(x.FieldName)).ToString();
like image 30
Siddhartha Avatar answered Nov 09 '22 12:11

Siddhartha