Ng Yang Yang
Ng Yang Yang

Reputation: 35

Sum the total in a column in datatable

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.

Upvotes: 0

Views: 710

Answers (2)

Tim Schmelter
Tim Schmelter

Reputation: 460058

The most flexible way is to use Enumerable.Sum:

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

Note that you need to add using System.Linq;.

You can also use the DataTable.Compute which syntax is not easy to remember and which is limited:

Int64 sum = (Int64) table.Compute("Sum (total)", null);

Upvotes: 1

CaldasGSM
CaldasGSM

Reputation: 3062

If you are you using a SQl server you can have the server calculate it and return you the sum..

SqlCommand cmd = new SqlCommand("SELECT SUM(Total) FROM MyTable", conn);
int nSum = (int)cmd.ExecuteScalar();

Upvotes: 0

Related Questions