0

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:

i

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • 5
    Rows 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 Answers1

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