You could use this Merge
method which merges the schema of two DataTables
and joins data on row-index(if both tables contain a column, the data of table1 will be taken as requested):
public static DataTable MergeOnRowIndex(DataTable table1, DataTable table2)
{
var data = table1.AsEnumerable()
.Select((r, i) => new
{
Row1 = r,
Row2 = i >= table2.Rows.Count ? null : table2.Rows[i]
});
DataTable table3 = new DataTable();
foreach (DataColumn col in table1.Columns)
{
table3.Columns.Add(col.ColumnName, col.DataType);
}
foreach(DataColumn col in table2.Columns)
if(!table3.Columns.Contains(col.ColumnName))
table3.Columns.Add(col.ColumnName, col.DataType);
if(data.Any())
{
foreach(var x in data)
{
var newRow = table3.Rows.Add();
for (int i = 0; i < table1.Columns.Count; i++)
{
newRow[i] = x.Row1.ItemArray[i];
}
if (x.Row2 != null)
{
for (int i = table1.Columns.Count; i < table3.Columns.Count; i++)
{
DataColumn currentColumn = table3.Columns[i];
newRow[currentColumn.ColumnName] = x.Row2[currentColumn.ColumnName];
}
}
}
}
return table3;
}
Here i've used the method to get your desired result on your sample data:
var table = new DataTable();
table.Columns.Add("Name");
table.Columns.Add("LastName");
var otherTable = new DataTable();
otherTable.Columns.Add("Name");
otherTable.Columns.Add("Product");
table.Rows.Add("a","aa");
table.Rows.Add("b","bb");
otherTable.Rows.Add("s","dd");
otherTable.Rows.Add("a","ss");
DataTable result = MergeOnRowIndex(table, otherTable);