Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to calculate(sum up) an a row value of an datatable

Tags:

c#

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

like image 249
happysmile Avatar asked Dec 17 '22 22:12

happysmile


2 Answers

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.

like image 120
Chris Anderson Avatar answered Jan 07 '23 21:01

Chris Anderson


There is buit-in method in DataTable object: DataTable.Compute

MSDN description

like image 43
meeron Avatar answered Jan 07 '23 20:01

meeron