Datatable - sum each cell in a row

There are many examples of how to get the sum of each cell in a column. I could not find an example of how to sum each cell in a row and add it to a new column called "Total", for example.

C # DataTable has DataTable1.Compute("SUM(["Column Name"])", "")

An example of what I would like to do below. However, I would also like to be able to exclude specific columns, since they cannot contain numbers.

enter image description here

Change . The table is dynamic and the number of columns can vary.

+4
source share
6 answers

You can use this loop:

table.Columns.Add("Total", typeof(decimal));
foreach (DataRow row in table.Rows)
{
    decimal rowSum = 0;
    foreach (DataColumn col in table.Columns)
    {
        if(!row.IsNull(col))
        {
            string stringValue = row[col].ToString();
            decimal d;
            if(decimal.TryParse(stringValue, out d))
                rowSum += d;
        }
    }
    row.SetField("Total", rowSum);
}

This should work with any type of column.

+5
source

DataTable . ""

DataTable1.Columns.Add("Total", typeof(Double));
DataTable1.Columns["Total"].Expression = "C1+C2+C3";
+3

:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Data;

namespace DynamicColumns
{
    class MainClass
    {
        public static void Main (string[] args)
        {
            Console.WriteLine ("Total all quantity columns");

            var dt = new DataTable ();
            dt.Columns.Add ("ProductName", typeof(string));
            dt.Columns.Add ("Qty1", typeof(int));
            dt.Columns.Add ("Qty2", typeof(int));
            dt.Columns.Add ("Qty3", typeof(int));

            {
                var dr = dt.NewRow ();
                dr ["ProductName"] = "Keyboard";
                dr ["Qty1"] = 2;
                dr ["Qty2"] = 5;
                dr ["Qty3"] = 6;
                dt.Rows.Add (dr);
            }

            {
                var dr = dt.NewRow ();
                dr ["ProductName"] = "Mouse";
                dr ["Qty1"] = 5;
                dr ["Qty2"] = 1;
                dr ["Qty3"] = 2;
                dt.Rows.Add (dr);
            }




            string expression = 

                string.Join (" + ", 
                    dt.Columns.OfType<DataColumn>()
                        .Where(x => x.DataType == typeof(int))
                        .Select(x => x.ColumnName)
                         .ToArray() );

            dt.Columns.Add("Total", typeof(int)).Expression = expression;


            Console.WriteLine ("Expression: {0}",expression);

            Console.WriteLine ("\nProduct and totals");
            foreach (var r in dt.Rows.OfType<DataRow>()) {
                Console.WriteLine ("{0} {1}", r["ProductName"], r["Total"]);
            }


        }
    }
}

:

Expression: Qty1 + Qty2 + Qty3

Product and totals
Keyboard 13
Mouse 8

I would venture to suggest that this expression (.Expression) is the most efficient solution compared to lambling our path to each row for each column and even compared to the loop of each row and each column

+1
source

I will try something like this:

foreach (DataRow row in table.Rows) {
   var rowSum = 0d;
   foreach (DataColumn column in row.Table.Columns) {
//if row[column] is number
        rowSum += Convert.ToDouble(row[column]));
//}
}
//at his point you have the the colums sum
}
0
source

Try it.

DataTable1.Columns.Add("Total", typeof(Double));

foreach (DataRow row in DataTable1.Rows) 
{
  int sum = row.Columns.Cast<DataColumn>().Sum(dc=>(int)row[dc]);
  row.SetField("Total", sum);
}
0
source
DataTable1.Columns.Add("C1", typeof(Double));
DataTable1.Columns.Add("C2", typeof(Double));
DataTable1.Columns.Add("C3", typeof(Double));
DataTable1.Columns.Add("Total", typeof(Double));
DataTable1.Columns["Total"].Expression = "C1+C2+C3";

This is the easiest way.!

0
source

All Articles