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;
}
Legacy Comments
david
2008-02-25 |
re: DataTable Relational Operators in C# - UNION Method Thank you! |
Mark Davies
2008-04-22 |
re: DataTable Relational Operators in C# - UNION Method doing a legacy application forgot that dt.merge was not around the the 1.1 days this is great thank you |
Royi by china
2008-07-29 |
re: DataTable Relational Operators in C# - UNION Method thank you for your share |
Rajani
2008-09-11 |
re: DataTable Relational Operators in C# - UNION Method Very good! Thanks. |