Search code examples
c#datatable

How to: Join 2 DataTables with same Row Count


I've got these two DataTables:

Table1: Columns->"Timestamp1,Result1" Row[0]->"someTime,someResult"

Table2: Columns->"Timestamp2,Result2" Row[0]->"someotherTime", "someotherResult"

Now I want to get a result table or string[] or string like this:

Table Result: Columns->"Timestamp1,Result1,Timestamp2,Result2" Row[0]->"someTime,someResult,someotherTime,someotherResult"

Is there a simple Way of doing this? Even if the tables got more rows then one?

I've allready got some solution for joining the Columns to a string:

StringBuilder sb = new StringBuilder();

        foreach (DataTable dt in data_set.Tables)
        {
            sb.Append(string.Join(",", dt.Columns.Cast<DataColumn>().Select(x => x.ColumnName).ToArray()));
            sb.Append(",");                              
        }

Output with the example tables will be a String like this >> "Timestamp1, Result1,Timestamp2,Result2"

So using linq could be possible, but unfortunately I dont get it...

Could someone help me please?

Best regards

Edit:

Both tables should have the same count of rows! Merge will not work, because it will just not join one rows from two different tables into a new single one. Merge will just output 2 Rows in the new table.


Solution

  • Ok I solved it on my own... this code looks for every column in dt2 and if it's not existing in dt1, it will start the copy process.

    foreach (DataColumn dc in data_table2.Columns)
            {
                //Only new Columns
                if (!data_table1.Columns.Contains(dc.ColumnName))
                {
                    //Add all new Columns to dt1
                    data_table1.Columns.Add(dc.ColumnName, dc.DataType);                    
    
                    //interate over all rows
                    foreach (DataRow dr in data_table2.Rows)
                    {
                        //Copy single value from  dt2 in dt1
                        data_table1.Rows[dr.Table.Rows.IndexOf(dr)][data_table1.Columns.IndexOf(dc.ColumnName)] = dr[dc.ColumnName];
                    }
                }
            }