0

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.

4

2 回答 2

1

最灵活的方法是使用Enumerable.Sum

Int64 sum = table.AsEnumerable().Sum(r => r.Field<int>("total"));

请注意,您需要添加using System.Linq;.

你也可以使用DataTable.Computewhich 语法不易记忆,且有限制:

Int64 sum = (Int64) table.Compute("Sum (total)", null);
于 2013-03-07T10:06:24.557 回答
0

如果您使用的是 SQl 服务器,您可以让服务器计算它并返回总和..

SqlCommand cmd = new SqlCommand("SELECT SUM(Total) FROM MyTable", conn);
int nSum = (int)cmd.ExecuteScalar();
于 2013-03-07T10:14:26.143 回答