I have a question. I need to sum up the total amount in a single column in datatable. How do i proceed with it?
For example
Total
2
3
4
5
9
10
i need to get a grand total of the whole column.
I have a question. I need to sum up the total amount in a single column in datatable. How do i proceed with it?
For example
Total
2
3
4
5
9
10
i need to get a grand total of the whole column.
最灵活的方法是使用Enumerable.Sum
:
Int64 sum = table.AsEnumerable().Sum(r => r.Field<int>("total"));
请注意,您需要添加using System.Linq;
.
你也可以使用DataTable.Compute
which 语法不易记忆,且有限制:
Int64 sum = (Int64) table.Compute("Sum (total)", null);
如果您使用的是 SQl 服务器,您可以让服务器计算它并返回总和..
SqlCommand cmd = new SqlCommand("SELECT SUM(Total) FROM MyTable", conn);
int nSum = (int)cmd.ExecuteScalar();