2

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
Leigh
  • 28,765
  • 10
  • 55
  • 103
francops henri
  • 507
  • 3
  • 17
  • 29

2 Answers2

1

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"]
        );
}
Alex Filipovici
  • 31,789
  • 6
  • 54
  • 78
0

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"))));
Community
  • 1
  • 1
Raphaël Althaus
  • 59,727
  • 6
  • 96
  • 122