Search code examples
c#system.data.datatable

How to merge two DataTables like this?


I have two datatables

dtTable1:
Name    Id  Contact
Gems    A1  8888880000
George  A2  0000008888

dtTable2:
Col1    Col2    Col3
XXX1    YYY1    ZZZ1
XXX2    YYY2    ZZZ2
XXX3    YYY3    ZZZ3
XXX4    YYY4    ZZZ4

My required DataTable is:

Name    Id  Contact         Col1    Col2    Col3
Gems    A1  8888880000  XXX1    YYY1    ZZZ1
George  A2  0000008888  XXX2    YYY2    ZZZ2
null    null   null     XXX3    YYY3    ZZZ3
null    null   null     XXX4    YYY4    ZZZ4

How can I do it with C#


Solution

  • Here you go. Might not be pretty but does the job. No matter which DataTable has more row it will add them.

    private static DataTable MergeTables(DataTable dt1, DataTable dt2)
    {
        DataTable merged = new DataTable();
    
        //copy column struct from dt1
        merged = dt1.Clone();
    
        //create columns from dt2
        foreach (DataColumn col in dt2.Columns)
        {
            merged.Columns.Add(col.ColumnName);
        }
    
        int rows;
    
        if (dt1.Rows.Count > dt2.Rows.Count)
        {
            rows = dt1.Rows.Count;
        }
        else
        {
            rows = dt2.Rows.Count;
        }
    
        for (int i = 0; i < rows; i++)
        {
            DataRow row = merged.NewRow();
    
            if ( i < dt1.Rows.Count)
            {
                for (int c = 0; c < dt1.Columns.Count; c++)
                {
                    row[c] = dt1.Rows[i][c];
                }
            }
    
            if (i < dt2.Rows.Count)
            {
                for (int c2 = dt1.Columns.Count; c2 < dt2.Columns.Count + dt1.Columns.Count; c2++)
                {
                    row[c2] = dt2.Rows[i][c2-dt1.Columns.Count];
                }
            }
            merged.Rows.Add(row);
        }
        return merged;
    }