I’m trying to join two DataTables together in a similar way to this question:
Inner join of DataTables in C#
I’m trying to get the output to be a single ‘combined’ table, with columns from both of the original tables. They will both have a datestamp column in common.
The answer given is good for DataTables with fixed columns, but what if they are created dynamically, and can have any number of columns, how can I join them?
e.g.
T1 (datestamp, t1Column1, t1Column2, t1ColumnN...)
T2 (datestamp, t2Column1, t2Column2, t2ColumnN...)
I would like to join to create the following:
J1 (datestamp, t1Column1, t1Column2, t1ColumnN, ..., t2Column1, t2Column2, t2ColumnN...)
Is this possible?
I found a solution which doesn’t rely on looping through the columns.
It uses the ‘Merge’ method, which I had previously dismissed as I thought both tables required the same structure.
First you need to create a primary key on the two data-tables:
Then add both tables to a data-set so a relationship can be added:
Next add the relationship between the two key columns in the data-set:
Finally you can now copy the first data-table into a new ‘combined’ version, and then merge in the second:
Note: The Merge method requires the second argument to be false or else it copies the structure but not the data of the second table.
This would then combine the following tables:
into a combined version based on the primary-key: