Wednesday, August 31, 2011

Merge Data Tables Easily

Many a times we face a situation where we have to merge data from multiple DataTable into single DataTable.  Previously we achieved this by iterating through the data rows in the DataTable and adding one by one into the single DataTable. This not only is memory consuming but also a bad practice.

To overcome this .net 4.0 now has a new DataTable function i.e. Merge(). The following program will make it more clear.

private static void DemonstrateMergeTable()
    DataTable table1 = new DataTable("Items");

    // Add columns
    DataColumn idColumn = new DataColumn("id", typeof(System.Int32));
    DataColumn itemColumn = new DataColumn("item", typeof(System.Int32));

    // Set the primary key column.
    table1.PrimaryKey = new DataColumn[] { idColumn };

    // Add RowChanged event handler for the table.
    table1.RowChanged += new 

    // Add ten rows.
    DataRow row;
    for (int i = 0; i <= 9; i++)
        row = table1.NewRow();
        row["id"] = i;
        row["item"] = i;

    // Accept changes.
    PrintValues(table1, "Original values");

    // Create a second DataTable identical to the first.
    DataTable table2 = table1.Clone();

    // Add column to the second column, so that the 
    // schemas no longer match.
    table2.Columns.Add("newColumn", typeof(System.String));

    // Add three rows. Note that the id column can't be the 
    // same as existing rows in the original table.
    row = table2.NewRow();
    row["id"] = 14;
    row["item"] = 774;
    row["newColumn"] = "new column 1";

    row = table2.NewRow();
    row["id"] = 12;
    row["item"] = 555;
    row["newColumn"] = "new column 2";

    row = table2.NewRow();
    row["id"] = 13;
    row["item"] = 665;
    row["newColumn"] = "new column 3";

    // Merge table2 into the table1.
    table1.Merge(table2, false, MissingSchemaAction.Add);
    PrintValues(table1, "Merged With table1, schema added");


private static void Row_Changed(object sender, 
    DataRowChangeEventArgs e)
    Console.WriteLine("Row changed {0}\t{1}", e.Action, 

private static void PrintValues(DataTable table, string label)
    // Display the values in the supplied DataTable:
    foreach (DataRow row in table.Rows)
        foreach (DataColumn col in table.Columns)
            Console.Write("\t " + row[col].ToString());


Related Posts with Thumbnails