Reputation: 304
I have two DataTables. The columns of the first table are
A B C D E
The Columns of the second table are
B C F D E G
I want to copy the data of all the columns from the first Table whose name exists in the second Table.
My Table is quite big so I don't want to assign it Column by Column
I am doing something like that (only snippet)
foreach (string colname in sourceColumnNames)
{
if (!targetColumnNames.Contains(colname)) continue;
// There are other steps as well
tRow[colname] = sRow[colname];
}
But it is not very optimal.
I am trying to do it using ItemArray. So I can copy the whole array(only the columns I need) at once. My idea is to match columns name between the source and target table and store it in the dictionary and make an item array from that dictionary.
Is there any other optimal way of copying the specfic columns between 2 data tables with out going through each column
Upvotes: 1
Views: 1722
Reputation: 3018
You can use DataTable.Load
method. It copies the source rows to destination table and you don't have to worry about columns mapping. An example how to do that:
dataTable2.Load(dataTable1.CreateDataReader());
For more information about DataTable.Load
look here
Upvotes: 1
Reputation: 11389
Based on your example you are checking common columns for every row. Since these columns are the same for every row you only need to do this once. Here is my idea of solving it:
First step is to create a mapping of columns from table 1 to table 2:
//Create a mapping
List<Tuple<int, int>> columnMappings = new List<Tuple<int, int>>();
for (int dt1ColumnIndex = 0; dt1ColumnIndex < dt1.Columns.Count; dt1ColumnIndex++)
{
string columnName = dt1.Columns[dt1ColumnIndex].ColumnName;
if (dt2.Columns.Contains(columnName) == true)
{
int dt2ColumnIndex = dt2.Columns.IndexOf(columnName);
columnMappings.Add(new Tuple<int, int>(dt1ColumnIndex, dt2ColumnIndex));
}
}
Now you are able to iterate all rows of the first table creating new rows to table 2:
//Add all rows from table 1 to table two based on the mapping
foreach (DataRow dt1Row in dt1.Rows)
{
DataRow dt2Row = dt2.NewRow();
foreach (Tuple<int, int> columnMapping in columnMappings)
{
dt2Row[columnMapping.Item2] = dt1Row[columnMapping.Item1];
}
dt2.Rows.Add(dt2Row);
}
Upvotes: 0