c#

c#两个datatable怎么合并

小亿
95
2024-09-03 10:05:25
栏目: 编程语言

在C#中,可以使用DataTable.Merge()方法将两个DataTable合并。以下是一个简单的示例:

using System;
using System.Data;

class Program
{
    static void Main()
    {
        // 创建第一个 DataTable
        DataTable table1 = new DataTable("Table1");
        table1.Columns.Add("ID", typeof(int));
        table1.Columns.Add("Name", typeof(string));
        table1.Rows.Add(1, "张三");
        table1.Rows.Add(2, "李四");

        // 创建第二个 DataTable
        DataTable table2 = new DataTable("Table2");
        table2.Columns.Add("ID", typeof(int));
        table2.Columns.Add("Age", typeof(int));
        table2.Rows.Add(1, 25);
        table2.Rows.Add(2, 30);

        // 合并两个 DataTable
        table1.Merge(table2);

        // 显示合并后的 DataTable
        Console.WriteLine("合并后的 DataTable:");
        Console.WriteLine("ID\tName\tAge");
        foreach (DataRow row in table1.Rows)
        {
            Console.WriteLine($"{row["ID"]}\t{row["Name"]}\t{row["Age"]}");
        }
    }
}

注意:在合并之前,请确保两个DataTable具有相同的主键列。如果没有主键列,可以使用DataTable.PrimaryKey属性设置主键列。

此外,Merge()方法还有一个重载版本,可以接受一个bool参数,用于指定是否保留源表中的原始数据。如果为true,则在目标表中保留原始数据;如果为false,则覆盖目标表中的原始数据。默认值为false

0
看了该问题的人还看了