How to calculate sum of a DataTable's Column in LINQ (to Dataset)?
100,482
Solution 1
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);
Solution 2
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();
Author by
Admin
Updated on December 06, 2020Comments
-
Admin over 3 years
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?
-
Viktor Vix Jančík over 13 yearsNote that you need the System.Data.DataSetExtensions Assembly for the above to work.
-
JohnB over 10 years@kervin: also, you need to make sure this is on top of your code file:
using System.Linq;
-
Shaiju T over 8 yearsjust to understand and if i am correct, when you say
typed
andun-typed
does it mean typed view and un-typed view in asp mvc , i mean the ViewModel class that we create ?