Home > front end >  How to merge multiple DataTables
How to merge multiple DataTables

Time:12-30

When I want to join two tables it goes down one row. How can I solve this?

public DataTable MergeTables()
{
    var dataTable1 = new DataTable();
    dataTable1.Columns.Add("Id");
    dataTable1.Columns.Add("Name");
    dataTable1.Columns.Add("Surname");
    dataTable1.Rows.Add("1", "Mike", "Tyson");
    dataTable1.Rows.Add("2", "John", "Wick");

    var dataTable2 = new DataTable();
    dataTable2.Columns.Add("Country");
    dataTable2.Columns.Add("Age");
    dataTable2.Rows.Add("America", "35");
    dataTable2.Rows.Add("Brasil", "50");

    dataTable1.Merge(dataTable2);
    return dataTable1;
}

Output:

CodePudding user response:

Merge requires primary key to match the records:

var dataTable1 = new DataTable();
dataTable1.Columns.Add("Id");
dataTable1.Columns.Add("Name");
dataTable1.Columns.Add("Surname");
dataTable1.PrimaryKey = new [] { dataTable1.Columns["Id"] }; // set PK

dataTable1.Rows.Add("1", "Mike", "Tyson");
dataTable1.Rows.Add("2", "John", "Wick");

var dataTable2 = new DataTable();
dataTable2.Columns.Add("Id"); // add PK column
dataTable2.Columns.Add("Country");
dataTable2.Columns.Add("Age");
dataTable2.PrimaryKey = new [] { dataTable2.Columns["Id"] }; // set PK

dataTable2.Rows.Add("1", "America", "35"); // add PK value
dataTable2.Rows.Add("2", "Brasil", "50"); // add PK value

dataTable1.Merge(dataTable2);
  • Related