ADO.NET 2's DataTable.Merge

OK, so its not ground breaking, earth shattering nor will it solve world hunger … but I am pretty stoked over the addition of the Merge method to the DataTable object in ADO.NET 2. It has always been an annoyance of mine that when I want to merge a DataTable into another one that I have to have a DataSet to perform the operation. What if I don’t have nor want a DataSet? Well, in ADO.NET 1.x you have to create a DataSet anyway. I know its just an extra line of code or 2, but its the point of creating an object that really serves no purpose in my context that bothers me. OK, so this is not a huge issue by itself but again I feel like it strays from sound development practices. If the DataSet is already there … fine.

In the following code sample I set up 2 DataTable objects manually and then merge them. Unfortunately, I have to create a DataSet to perform the merge.

<FIELDSET> <LEGEND>ADO.NET 1.1 - DataSet.Merge</LEGEND> private void Button1_Click( object sender, System.EventArgs e)
    // Set up a DataTable
    DataTable oDt= new DataTable("Colors");
    oDt.Columns.Add("ColorID", System.Type.GetType("System.Int32"));
    oDt.Columns.Add("ColorName", System.Type.GetType("System.String"));
    oDt.PrimaryKey = new DataColumn[]{oDt.Columns["ColorID"]};
    oDt.Rows.Add(new object[]{1,"Red"});
    oDt.Rows.Add(new object[]{2,"Teal"});
    oDt.Rows.Add(new object[]{3,"Yellow"});

    // Set up a another DataTable that I will use to Merge
    DataTable oDtMoreColors= new DataTable("Colors");
    oDtMoreColors.Columns.Add("ColorID", System.Type.GetType("System.Int32"));
    oDtMoreColors.Columns.Add("ColorName", System.Type.GetType("System.String"));
    oDtMoreColors.PrimaryKey = new DataColumn[]{oDtMoreColors.Columns["ColorID"]};
    oDtMoreColors.Rows.Add(new object[]{1,"Red"});
    oDtMoreColors.Rows.Add(new object[]{2,"Blue"});
    oDtMoreColors.Rows.Add(new object[]{4,"Green"});

    // Create a DataSet so I can merge the DataTable objects
    DataSet oDs = new DataSet("WhyOhWhy");

In ADO.NET 2 I can skip creating the DataSet and instead use the following line of code.

<FIELDSET><LEGEND>ADO.NET 2 - DataTable.Merge</LEGEND>     oDt.Merge(oDtMoreColors); </FIELDSET>

While some topics like MARS are grabbing more of the press in ADO.NET 2, tweaks like the DataTable Merge method are flying under the radar. After all, I use these types of features all the time so if we can make it work better, then I am all for it.

Tweet Post Share Update RSS

Hi, I'm John Papa. I author this blog, create courses for Pluralsight and am a Google Developer Expert and Microsoft Regional Director. I travel speaking at events and train technology thought leaders