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