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.

Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
Ng Yang Yang
  • 35
  • 1
  • 6
  • Have you tried anything yourself first? Do you have any code to show? – Jason Evans Mar 07 '13 at 10:05
  • Check these answers out: http://stackoverflow.com/questions/5601752/how-to-sum-columns-in-a-datatable http://stackoverflow.com/questions/5892993/how-to-calculate-the-sum-of-the-datatable-column-in-asp-net – gdp Mar 07 '13 at 10:06

2 Answers2

1

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);
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
  • What is that variable r that u mention in enumerable.Sum? – Ng Yang Yang Mar 07 '13 at 16:17
  • @NgYangYang: That is the projected `DataRow` since [`DataTable.AsEnumerable`](http://msdn.microsoft.com/en-us/library/system.data.datatableextensions.asenumerable.aspx) returns an `IEnumerable`. – Tim Schmelter Mar 07 '13 at 16:20
0

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();
CaldasGSM
  • 3,032
  • 16
  • 26