I have 2 data tables, which I do not know their list of data columns. This list must be extracted at run time, and be used for the full outer join.
When using these
Based on Matthew's answer, I've created a function that accepts more than 2 datatables. I hope it helps:
Usage:
var table123 = FullOuterJoinDataTables(table1, table2, table3);
Here is the function source:
public DataTable FullOuterJoinDataTables(params DataTable[] datatables) // supports as many datatables as you need.
{
DataTable result = datatables.First().Clone();
var commonColumns = result.Columns.OfType();
foreach (var dt in datatables.Skip(1))
{
commonColumns = commonColumns.Intersect(dt.Columns.OfType(), new DataColumnComparer());
}
result.PrimaryKey = commonColumns.ToArray();
foreach (var dt in datatables)
{
result.Merge(dt, false, MissingSchemaAction.AddWithKey);
}
return result;
}
/* also create this class */
public class DataColumnComparer : IEqualityComparer
{
public bool Equals(DataColumn x, DataColumn y) => x.Caption == y.Caption;
public int GetHashCode(DataColumn obj) => obj.Caption.GetHashCode();
}