I need to merge/join datatables on C# with a common column.
I am aware of many examples and the questions on the same topic that have been asked. I have not found any that answer my question though.
Below is the code i am using.
The code only allows for one common column based on the data of on datatable. I need a common column, but it needs to consider any other "Account#" may be used in another datatable and add it into the common column.
Also the code only allows for merging of 2 datatables. i need to merge 31 datatables, to merge 1 datatable for each day of the month.
I have a datatable for each day of the month, dt_docDAY01, dt_docDAY02, dt_docDAY03 etc.
each datatable contains an account number "Account#" and a balance stored in a column refering to the day "DAY01", "DAY02", etc.
Can you tell me how to change the code so that i will include all accounts from all tables.
Also, how i would merge all the datatables in this code, so i dont have to run this same code 31 times.
' string id = "Account#";
var tableJoinedDAY02 = dt_docDAY01_GROUPED.Clone(); // create columns from table1
// add columns from table2 except id
foreach (DataColumn column in dt_docDAY02_GROUPED.Columns)
{
if (column.ColumnName != id)
tableJoinedDAY02.Columns.Add(column.ColumnName, column.DataType);
}
tableJoinedDAY02.BeginLoadData();
foreach (DataRow row1 in dt_docDAY01_GROUPED.Rows)
{
foreach (DataRow row2 in dt_docDAY02_GROUPED.Rows)
{
if (row1.Field<string>(id) == row2.Field<string>(id))
{
var list = row1.ItemArray.ToList(); // items from table1
// add items from table2 except id
foreach (DataColumn column in dt_docDAY02_GROUPED.Columns)
if (column.ColumnName != id)
list.Add(row2[column]);
tableJoinedDAY02.Rows.Add(list.ToArray());
}
}
}
tableJoinedDAY02.EndLoadData();`
Table1
Account# | Day01 1234 | 11 4567 | 22 0909 | 33
Table2
Account# | Day02 1234 | 12 0909 | 34 5578 | 99 0065 | 34
Table3
Account# | Day03 1234 | 13 7777 | 44
Expected Outcome Merged Table
Table1
Account# | Day01 | Day02 | Day03 1234 | 11 | 12 | 13 4567 | 22 | 0 | 0 0909 | 33 | 34 | 0 5578 | 0 | 99 | 0 0065 | 0 | 34 | 0 7777 | 0 | 0 | 44