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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With