I need help: how to join two datatables in C# with column names different not merge, just join right or left, just get dtResult from dtA join with dtB like this below:
Asked
Active
Viewed 2,785 times
0
-
5Rows are supposed to contain related data, that structure makes no sense. How did you decide to put "bird" with "apple" instead of "mango"? – Crowcoder Nov 14 '17 at 15:56
-
I think that is not a join, but rather a zip of two sets of data. – Willy David Jr Nov 14 '17 at 15:57
-
@Crowcoder: sure, but sometimes the relationship is the index. Note that `DataTables` are not database-tables. They are just in memory collections like an array or list where each row can be accessed via index. – Tim Schmelter Nov 14 '17 at 16:12
1 Answers
0
If you mean join by index, it's more a zip of two DataTables
. You could use this method:
public static DataTable MergeTablesByIndex(DataTable t1, DataTable t2)
{
if (t1 == null || t2 == null) throw new ArgumentNullException("t1 or t2", "Both tables must not be null");
DataTable t3 = t1.Clone(); // first add columns from table1
foreach (DataColumn col in t2.Columns)
{
string newColumnName = col.ColumnName;
int colNum = 1;
while (t3.Columns.Contains(newColumnName))
{
newColumnName = string.Format("{0}_{1}", col.ColumnName, ++colNum);
}
t3.Columns.Add(newColumnName, col.DataType);
}
var mergedRows = t1.AsEnumerable().Zip(t2.AsEnumerable(),
(r1, r2) => r1.ItemArray.Concat(r2.ItemArray).ToArray());
foreach (object[] rowFields in mergedRows)
t3.Rows.Add(rowFields);
return t3;
}
I haven't written this from scratch, it's second part of an older answer of me.

Tim Schmelter
- 450,073
- 74
- 686
- 939
-
i only get one rows, why if i want get all rows ? if number of rows in dtA=100 and number of rows in dtB = 5 – Muhammad Ibnu Saefullah Nov 15 '17 at 02:57
-
@MuhammadIbnuSaefullah: you still have issues here or does it work now? – Tim Schmelter Nov 15 '17 at 08:36