Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merge 2 DataTables and store in a new one

Tags:

c#

datatable

People also ask

How do you merge DataTables?

Merge the specified DataTable with the current DataTable , indicating whether to preserve changes and how to handle missing schema in the current DataTable . Merge the specified DataTable with the current DataTable , indicating whether to preserve changes in the current DataTable .

How do you store multiple DataTables in a DataSet?

Create multiple DataTable objects and add them to DataSet using the AddRange() method of the DataTableCollection of the DataSet.


The Merge method takes the values from the second table and merges them in with the first table, so the first will now hold the values from both.

If you want to preserve both of the original tables, you could copy the original first, then merge:

dtAll = dtOne.Copy();
dtAll.Merge(dtTwo);

Instead of dtAll = dtOne.Copy(); in Jeromy Irvine's answer you can start with an empty DataTable and merge one-by-one iteratively:

dtAll = new DataTable();
...
dtAll.Merge(dtOne);
dtAll.Merge(dtTwo);
dtAll.Merge(dtThree);
...

and so on.

This technique is useful in a loop where you want to iteratively merge data tables:

DataTable dtAllCountries = new DataTable();

foreach(String strCountry in listCountries)
{
    DataTable dtCountry = getData(strCountry); //Some function that returns a data table
    dtAllCountries.Merge(dtCountry);
}

dtAll = dtOne.Copy();
dtAll.Merge(dtTwo,true);

The parameter TRUE preserve the changes.

For more details refer to MSDN.


DataTable dtAll = new DataTable();
DataTable dt= new DataTable();
foreach (int id in lst)
{
    dt.Merge(GetDataTableByID(id)); // Get Data Methode return DataTable
}
dtAll = dt;