DataTable Relational Operators in C# - UNION Method

The implementation of the UNION operator is equivalent to the TSQL expresion UNION ALL
***WARNING****This means that duplicates can appear

The First table is used to construct the new DataTables columns, so in effect, the columns in the Second table only need to have the same Data Types and not both Name and Data Type.

There is only the one signature for this method.
In summary the code works as follows:

  Create new empty table
  Add columns to empty table.
   Loop through First table and add rows
   Loop through Second table and add rows
   Return Table.

public static DataTable Union (DataTable First, DataTable Second)

{

      //Result table

      DataTable table = new DataTable("Union");

      //Build new columns

      DataColumn[] newcolumns = new DataColumn[First.Columns.Count];

      for(int i=0; i < First.Columns.Count; i++)

      {

            newcolumns[i] = new DataColumn(First.Columns[i].ColumnName, First.Columns[i].DataType);

      }

      //add new columns to result table

      table.Columns.AddRange(newcolumns);

      table.BeginLoadData();

      //Load data from first table

      foreach(DataRow row in First.Rows)

      {

            table.LoadDataRow(row.ItemArray,true);

      }

      //Load data from second table

      foreach(DataRow row in Second.Rows)

      {

            table.LoadDataRow(row.ItemArray,true);

      }

      table.EndLoadData();

      return table;

}

Print | posted on Thursday, January 15, 2004 11:04 AM

Feedback

# .NET C# DataTable Relational Operators

left by newt blog at 4/3/2004 10:53 PM Gravatar
Stumbled onto a blog, DavidM with some great C# code for data table relational operators. Contained herein is code for...

# re: DataTable Relational Operators in C# - UNION Method

left by david at 2/25/2008 6:32 PM Gravatar
Thank you!

# re: DataTable Relational Operators in C# - UNION Method

left by Mark Davies at 4/22/2008 7:00 PM Gravatar
doing a legacy application forgot that dt.merge was not around the the 1.1 days this is great thank you

# re: DataTable Relational Operators in C# - UNION Method

left by Royi by china at 7/29/2008 12:51 PM Gravatar
thank you for your share

# re: DataTable Relational Operators in C# - UNION Method

left by Rajani at 9/11/2008 12:54 AM Gravatar
Very good! Thanks.
Comments have been closed on this topic.