francops henri
francops henri

Reputation: 517

Add columns of datatables in a dataset

I have a DataSet with 2 DataTable's. Each DataTable contains a column called "cost". I want to calculate the sum of all costs for the 2 tables in a table called Result table, like the example below. How can I do that?

Table 1
Name  | cost
balan |  6
gt    |  5

Table 2
Name  |  cost
balan |  2
gt    |  8

Result table
Name  | cost
balan | 8
gt    | 12

Upvotes: 2

Views: 6259

Answers (2)

Raphaël Althaus
Raphaël Althaus

Reputation: 60493

to get the result, you can do something like

var table1 = yourDataSet.Tables["Table 1"];
var table2 = yourDataSet.Tables["Table 2"];

var results = table1.AsEnumerable().Select(t1 => new {
                  name = t1.Field<string>("Name"),
                  cost = t1.Field<int>("cost")
              })
              .Concat(

              table2.AsEnumerable().Select(t2 => new {
                  name = t2.Field<string>("Name"),
                  cost = t2.Field<int>("cost")
              })
              )
              .GroupBy(m => m.name)
              .Select(g => new {
                 name = g.Key,
                 cost = g.Sum(x => x.cost)
              });

this won't give you a dataTable, but an IEnumerable. To transform an IEnumerable to a dataTable, see for example here

or easier, if table1 and table2 have same rows

var table1 = yourDataSet.Tables["Table 1"];
var table2 = yourDataSet.Tables["Table 2"];

var results = new DataTable();

results.Columns.Add("Name");
results.Columns.Add("cost", typeof(int));

table1.AsEnumerable().Concat(table2.AsEnumerable())
                .GroupBy(m => m.Field<string>("Name"))
                .Select(g => results.Rows.Add(g.Key, g.Sum(x => x.Field<int>("cost"))));

Upvotes: 0

Alex Filipovici
Alex Filipovici

Reputation: 32561

This is a way to do it:

DataTable dt1 = new DataTable();
DataTable dt2 = new DataTable();
DataTable results = new DataTable();

dt1.Columns.Add("Name");
dt1.Columns.Add("cost", typeof(int));
dt2.Columns.Add("Name");
dt2.Columns.Add("cost", typeof(int));
results.Columns.Add("Name");
results.Columns.Add("cost", typeof(int));

dt1.Rows.Add("balan", 6);
dt2.Rows.Add("balan", 2);
dt1.Rows.Add("gt", 5);
dt2.Rows.Add("gt", 8);


foreach (DataRow dr1 in dt1.Rows)
{
    results.Rows
        .Add(
            dr1["Name"], 
            (int)dr1["cost"] + (int)dt2.Select(String.Format("Name='{0}'", dr1["name"]))[0]["cost"]
        );
}

Upvotes: 1

Related Questions