1
votes

I have a DataTable of 4 columns A,B,C,D with 4 rows of data all containing integer values.I want to return a DataRow of A,B,C,D columns which contains the sum of individual A,B,C,D column's values. There is no filter, straight up total as do in an excel.

DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[4] { 
                            new DataColumn("A", typeof(int)),
                            new DataColumn("B", typeof(int)),
                            new DataColumn("C", typeof(int)),
                            new DataColumn("D", typeof(int)) 
                        });
dt.Rows.Add(1,1,1,1);
dt.Rows.Add(2,2,2,2);
dt.Rows.Add(3,3,3,3);
dt.Rows.Add(4,4,4,4);

The output data row must contain 4 columns of 10,10,10,10 values

1

1 Answers

1
votes

If you want a column (say Total), that has the sum of A,B,C,D of each row, add a computed column, like this,

DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[] {
                new DataColumn("A", typeof(int)),
                new DataColumn("B", typeof(int)),
                new DataColumn("C", typeof(int)),
                new DataColumn("D", typeof(int)),
                // add computed column in case you want to get sum of each row in a separate column
                new DataColumn("Total", typeof(int),"A+B+C+D")
            });
dt.Rows.Add(1, 1, 1, 1);
dt.Rows.Add(2, 2, 2, 2);
dt.Rows.Add(3, 3, 3, 3);
dt.Rows.Add(4, 4, 4, 4);

Total column has sum of individual columns

If you want the sum of each column in 4 variables (or whatever), use the DataTable.Compute method, like this,

//use DataTable.Compute to calculate sum or each column
var sumA = dt.Compute("SUM(A)", "");
var sumB = dt.Compute("SUM(B)", "");
var sumC = dt.Compute("SUM(C)", "");
var sumD = dt.Compute("SUM(D)", "");

Sum of each column

//since you want these added as new row in the datatable...
dt.Rows.Add(sumA, sumB, sumC, sumD);