Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sum columns in a dataTable?

Tags:

c#

vb.net

How can I get a sum for all the columns in a datatable? Say I had the following table. How can I calculate the "total" row? It should be easy to add total row to a datatable.

         Columns    hits     uniques    sigups, etc...
Rows                  
1                      12         1         23
2                       1         0          5
3                       6         2          9


total                  19          3        37

Update

I ended up with this. It was the only thing I could get to work.

 For Each col As DataColumn In TotalsTable.Columns    
    If col.DataType.Name = "DateTime" Then
            count = count + 1
                Continue For
        End If

        Dim colTotal As Double = 0
        Dim value As Double

        For Each row As DataRow In TotalsTable.Rows
            If Double.TryParse(row(col), value) Then
                    colTotal += Double.Parse(row(col))
                    End If
        Next

    totalRow(count) = colTotal
        count = count + 1

  Next
like image 492
chobo Avatar asked Apr 08 '11 23:04

chobo


People also ask

How do you find the total of a DataTable?

sum() Sum the values in a data set. Fairly simply, this plug-in will take the data from an API result set and sum it, returning the summed value. The data can come from any data source, including column data, cells or rows.


2 Answers

There is also a way to do this without loops using the DataTable.Compute Method. The following example comes from that page. You can see that the code used is pretty simple.:

private void ComputeBySalesSalesID(DataSet dataSet)
{
    // Presumes a DataTable named "Orders" that has a column named "Total."
    DataTable table;
    table = dataSet.Tables["Orders"];

    // Declare an object variable. 
    object sumObject;
    sumObject = table.Compute("Sum(Total)", "EmpID = 5");
}

I must add that if you do not need to filter the results, you can always pass an empty string:

sumObject = table.Compute("Sum(Total)", "")
like image 174
Nicolas Avatar answered Oct 05 '22 19:10

Nicolas


Try this:

            DataTable dt = new DataTable();
            int sum = 0;
            foreach (DataRow dr in dt.Rows)
            {
                foreach (DataColumn dc in dt.Columns)
                {
                    sum += (int)dr[dc];
                }
            } 
like image 40
ysrb Avatar answered Oct 05 '22 19:10

ysrb