Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to calculate sum (Total) of DataTable Columns using C#

Tags:

c#

DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[3] { new DataColumn("EmployeeId", typeof(int)),
        new DataColumn("Name", typeof(string)),
        new DataColumn("Salary", typeof(int)) });
dt.Rows.Add(1, "John Hammond", 45000);
dt.Rows.Add(2, "Mudassar Khan", 32000);
dt.Rows.Add(3, "Robert Schidner", 19000);
dt.Rows.Add(3, "Suzanne Mathews", 18500);

This is my table and i want to add salary.

like image 395
Manish Singh Avatar asked Oct 28 '25 14:10

Manish Singh


1 Answers

Instead of dt.Compute you can also use LINQ:

int sum = dt.AsEnumerable().Sum(r => r.Field<int>("Salary"));

The nice thing with LINQ is that it's so easy to calculate the everage instead:

double average = dt.AsEnumerable().Average(r => r.Field<int>("Salary"));

or to get max salary:

int maxSalary = dt.AsEnumerable().Max(r => r.Field<int>("Salary"));

or to filter, count all salaries which are higher than 3000:

int countHighSalary = dt.AsEnumerable().Count(r => r.Field<int>("Salary") >= 3000);
like image 80
Tim Schmelter Avatar answered Oct 31 '25 05:10

Tim Schmelter



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!