i have an datatable like this. i am getting this data from an excel sheet and converted to datatable
id workedhours tfshours
1 3 2
2 5 5
3 .7 3
4 2 3.2
5 4.3 6.8
now i need the sum of the column workedhours and tfshours
how can i achive that is .there any builtin function to get the sum of teh column
i need the result like this in a new datatable
workedhours tfshours
15 20
any help would be greatly appreicated. thank you
Create a new Datatable and use the datatable.compute methods.
DataTable sumDataTable = new DataTable();
sumDataTable.Columns.Add("total", typeof(string));
sumDataTable.Columns.Add("workedhours", typeof(int));
sumDataTable.Columns.Add("tfshours", typeof(int));
DataRow row = sumDataTable.NewRow();
row["total"] = "Total";
row["workedhours"] = oldDataTable.Compute("Sum(workedhours)", "workedhours > 0");
row["tfshours"] = oldDataTable.Compute("Sum(tfshours)", "tfshours > 0");
sumDataTable.Rows.Add(row);
The second parameter, filter, determines which rows are used in the expression, but you could just put "" to select all rows.
There is buit-in method in DataTable object: DataTable.Compute
MSDN description
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