Merge two DataTables columns in C#.

We can merge two DataTables’ columns in C# using the Merge() method. Here is a simple example:

DataTable dt1 = new DataTable();
DataTable dt2 = new DataTable();

// 添加列到dt1
dt1.Columns.Add("ID", typeof(int));
dt1.Columns.Add("Name", typeof(string));

// 添加列到dt2
dt2.Columns.Add("ID", typeof(int));
dt2.Columns.Add("Age", typeof(int));

// 添加行到dt1
dt1.Rows.Add(1, "John");
dt1.Rows.Add(2, "Mary");

// 添加行到dt2
dt2.Rows.Add(1, 25);
dt2.Rows.Add(2, 30);

// 合并两个DataTable的列
dt1.Merge(dt2);

// 打印合并后的DataTable
foreach (DataRow row in dt1.Rows)
{
    foreach (DataColumn col in dt1.Columns)
    {
        Console.Write(row[col] + "\t");
    }
    Console.WriteLine();
}

The output is:

1   John    25
2   Mary    30

In the above example, we first create two DataTables, dt1 and dt2, and add different columns and rows to them respectively. Then we merge the columns of dt2 into dt1 by calling the Merge() method of dt1. Finally, we loop through the rows and columns of dt1 to print out the merged DataTable.

bannerAds