datatable合并列
时间: 2023-07-22 17:14:35 浏览: 50
要合并 DataTable 中的列,可以使用 Merge 方法。 Merge 方法的语法如下:
```csharp
table.Merge(dataTable, preserveChanges, missingSchemaAction);
```
其中,table 是要合并到的 DataTable,dataTable 是要从中合并数据的 DataTable。 preserveChanges 和 missingSchemaAction 是可选参数。
下面是一个示例代码,演示如何将 DataTable 中的两列合并为一列:
```csharp
DataTable table = new DataTable();
table.Columns.Add("Name");
table.Columns.Add("Age");
table.Rows.Add("Tom", 20);
table.Rows.Add("Jerry", 18);
// 新建一个空的DataTable,只包含一列
DataTable newTable = new DataTable();
newTable.Columns.Add("Info");
// 遍历原DataTable,将Name和Age合并为一个字符串,然后添加到新DataTable中
foreach (DataRow row in table.Rows)
{
string info = row["Name"].ToString() + " (" + row["Age"].ToString() + ")";
newTable.Rows.Add(info);
}
// 打印新DataTable的内容
foreach (DataRow row in newTable.Rows)
{
Console.WriteLine(row["Info"].ToString());
}
```
输出结果为:
```
Tom (20)
Jerry (18)
```