您现在的位置是:首页 >技术杂谈 >C#的DataTable类精简汇总网站首页技术杂谈

C#的DataTable类精简汇总

零壹电子 2026-04-05 12:01:04
简介C#的DataTable类精简汇总

目录

一、DataTable概述

1.创建 DataTable

2.添加行

3.修改行

4.删除行

5.查询行

6.排序行

7.合并 DataTable

8.克隆 DataTable

9.复制 DataTable

10.使用 DataView 过滤和排序

11.使用 DataTable 的事件

12.使用 DataTable 的约束

13.使用 DataTable 的表达式列

14.使用 DataTable 的 XML 序列化

15.使用 DataTable 的 JSON 序列化

二、总结


一、DataTable概述

C# 中的 DataTable 是一个非常重要的类,用于在内存中存储和操作数据。它类似于数据库中的表,具有行和列的结构。下面是一个详细的教程,涵盖了 DataTable 的常见操作方法,并提供了相应的示例代码。

1.创建 DataTable

首先,我们需要创建一个 DataTable 对象,并为其添加列。

using System;
using System.Data;

class Program
{
    static void Main()
    {
        // 创建 DataTable
        DataTable table = new DataTable("MyTable");

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

        // 打印表结构
        foreach (DataColumn column in table.Columns)
        {
            Console.WriteLine(column.ColumnName + " - " + column.DataType);
        }
    }
}

2.添加行

我们可以使用 NewRow() 方法创建新行,并将其添加到 DataTable 中。

using System;
using System.Data;

class Program
{
    static void Main()
    {
        DataTable table = new DataTable("MyTable");
        table.Columns.Add("ID", typeof(int));
        table.Columns.Add("Name", typeof(string));
        table.Columns.Add("Age", typeof(int));

        // 添加行
        DataRow row1 = table.NewRow();
        row1["ID"] = 1;
        row1["Name"] = "Alice";
        row1["Age"] = 25;
        table.Rows.Add(row1);

        DataRow row2 = table.NewRow();
        row2["ID"] = 2;
        row2["Name"] = "Bob";
        row2["Age"] = 30;
        table.Rows.Add(row2);

        // 打印行数据
        foreach (DataRow row in table.Rows)
        {
            Console.WriteLine($"{row["ID"]}, {row["Name"]}, {row["Age"]}");
        }
    }
}

3.修改行

我们可以通过索引或条件查找行,并修改其数据。

using System;
using System.Data;

class Program
{
    static void Main()
    {
        DataTable table = new DataTable("MyTable");
        table.Columns.Add("ID", typeof(int));
        table.Columns.Add("Name", typeof(string));
        table.Columns.Add("Age", typeof(int));

        DataRow row1 = table.NewRow();
        row1["ID"] = 1;
        row1["Name"] = "Alice";
        row1["Age"] = 25;
        table.Rows.Add(row1);

        DataRow row2 = table.NewRow();
        row2["ID"] = 2;
        row2["Name"] = "Bob";
        row2["Age"] = 30;
        table.Rows.Add(row2);

        // 修改行数据
        DataRow rowToUpdate = table.Rows[0];
        rowToUpdate["Name"] = "Alice Smith";
        rowToUpdate["Age"] = 26;

        // 打印修改后的行数据
        foreach (DataRow row in table.Rows)
        {
            Console.WriteLine($"{row["ID"]}, {row["Name"]}, {row["Age"]}");
        }
    }
}

4.删除行

我们可以通过 Remove() 或 Delete() 方法删除行。

using System;
using System.Data;

class Program
{
    static void Main()
    {
        DataTable table = new DataTable("MyTable");
        table.Columns.Add("ID", typeof(int));
        table.Columns.Add("Name", typeof(string));
        table.Columns.Add("Age", typeof(int));

        DataRow row1 = table.NewRow();
        row1["ID"] = 1;
        row1["Name"] = "Alice";
        row1["Age"] = 25;
        table.Rows.Add(row1);

        DataRow row2 = table.NewRow();
        row2["ID"] = 2;
        row2["Name"] = "Bob";
        row2["Age"] = 30;
        table.Rows.Add(row2);

        // 删除行
        table.Rows[0].Delete(); // 标记为删除
        table.AcceptChanges();  // 提交删除

        // 打印剩余行数据
        foreach (DataRow row in table.Rows)
        {
            Console.WriteLine($"{row["ID"]}, {row["Name"]}, {row["Age"]}");
        }
    }
}

5.查询行

我们可以使用 Select() 方法查询符合条件的行。

using System;
using System.Data;

class Program
{
    static void Main()
    {
        DataTable table = new DataTable("MyTable");
        table.Columns.Add("ID", typeof(int));
        table.Columns.Add("Name", typeof(string));
        table.Columns.Add("Age", typeof(int));

        DataRow row1 = table.NewRow();
        row1["ID"] = 1;
        row1["Name"] = "Alice";
        row1["Age"] = 25;
        table.Rows.Add(row1);

        DataRow row2 = table.NewRow();
        row2["ID"] = 2;
        row2["Name"] = "Bob";
        row2["Age"] = 30;
        table.Rows.Add(row2);

        // 查询行
        DataRow[] rows = table.Select("Age > 26");

        // 打印查询结果
        foreach (DataRow row in rows)
        {
            Console.WriteLine($"{row["ID"]}, {row["Name"]}, {row["Age"]}");
        }
    }
}

6.排序行

我们可以使用 DefaultView.Sort 属性对行进行排序。

using System;
using System.Data;

class Program
{
    static void Main()
    {
        DataTable table = new DataTable("MyTable");
        table.Columns.Add("ID", typeof(int));
        table.Columns.Add("Name", typeof(string));
        table.Columns.Add("Age", typeof(int));

        DataRow row1 = table.NewRow();
        row1["ID"] = 1;
        row1["Name"] = "Alice";
        row1["Age"] = 25;
        table.Rows.Add(row1);

        DataRow row2 = table.NewRow();
        row2["ID"] = 2;
        row2["Name"] = "Bob";
        row2["Age"] = 30;
        table.Rows.Add(row2);

        // 排序
        table.DefaultView.Sort = "Age DESC";

        // 打印排序后的行数据
        foreach (DataRowView rowView in table.DefaultView)
        {
            DataRow row = rowView.Row;
            Console.WriteLine($"{row["ID"]}, {row["Name"]}, {row["Age"]}");
        }
    }
}

7.合并 DataTable

我们可以使用 Merge() 方法合并两个 DataTable

using System;
using System.Data;

class Program
{
    static void Main()
    {
        DataTable table1 = new DataTable("MyTable");
        table1.Columns.Add("ID", typeof(int));
        table1.Columns.Add("Name", typeof(string));
        table1.Columns.Add("Age", typeof(int));

        DataRow row1 = table1.NewRow();
        row1["ID"] = 1;
        row1["Name"] = "Alice";
        row1["Age"] = 25;
        table1.Rows.Add(row1);

        DataTable table2 = new DataTable("MyTable");
        table2.Columns.Add("ID", typeof(int));
        table2.Columns.Add("Name", typeof(string));
        table2.Columns.Add("Age", typeof(int));

        DataRow row2 = table2.NewRow();
        row2["ID"] = 2;
        row2["Name"] = "Bob";
        row2["Age"] = 30;
        table2.Rows.Add(row2);

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

        // 打印合并后的行数据
        foreach (DataRow row in table1.Rows)
        {
            Console.WriteLine($"{row["ID"]}, {row["Name"]}, {row["Age"]}");
        }
    }
}

8.克隆 DataTable

我们可以使用 Clone() 方法克隆 DataTable 的结构。

using System;
using System.Data;

class Program
{
    static void Main()
    {
        DataTable table1 = new DataTable("MyTable");
        table1.Columns.Add("ID", typeof(int));
        table1.Columns.Add("Name", typeof(string));
        table1.Columns.Add("Age", typeof(int));

        DataRow row1 = table1.NewRow();
        row1["ID"] = 1;
        row1["Name"] = "Alice";
        row1["Age"] = 25;
        table1.Rows.Add(row1);

        // 克隆 DataTable
        DataTable table2 = table1.Clone();

        // 打印克隆后的表结构
        foreach (DataColumn column in table2.Columns)
        {
            Console.WriteLine(column.ColumnName + " - " + column.DataType);
        }
    }
}

9.复制 DataTable

我们可以使用 Copy() 方法复制 DataTable 的结构和数据。

using System;
using System.Data;

class Program
{
    static void Main()
    {
        DataTable table1 = new DataTable("MyTable");
        table1.Columns.Add("ID", typeof(int));
        table1.Columns.Add("Name", typeof(string));
        table1.Columns.Add("Age", typeof(int));

        DataRow row1 = table1.NewRow();
        row1["ID"] = 1;
        row1["Name"] = "Alice";
        row1["Age"] = 25;
        table1.Rows.Add(row1);

        // 复制 DataTable
        DataTable table2 = table1.Copy();

        // 打印复制后的行数据
        foreach (DataRow row in table2.Rows)
        {
            Console.WriteLine($"{row["ID"]}, {row["Name"]}, {row["Age"]}");
        }
    }
}

10.使用 DataView 过滤和排序

DataView 是 DataTable 的一个视图,可以用于过滤和排序数据。

using System;
using System.Data;

class Program
{
    static void Main()
    {
        DataTable table = new DataTable("MyTable");
        table.Columns.Add("ID", typeof(int));
        table.Columns.Add("Name", typeof(string));
        table.Columns.Add("Age", typeof(int));

        DataRow row1 = table.NewRow();
        row1["ID"] = 1;
        row1["Name"] = "Alice";
        row1["Age"] = 25;
        table.Rows.Add(row1);

        DataRow row2 = table.NewRow();
        row2["ID"] = 2;
        row2["Name"] = "Bob";
        row2["Age"] = 30;
        table.Rows.Add(row2);

        // 创建 DataView
        DataView view = new DataView(table);
        view.RowFilter = "Age > 26";
        view.Sort = "Name DESC";

        // 打印过滤和排序后的行数据
        foreach (DataRowView rowView in view)
        {
            DataRow row = rowView.Row;
            Console.WriteLine($"{row["ID"]}, {row["Name"]}, {row["Age"]}");
        }
    }
}

11.使用 DataTable 的事件

DataTable 提供了多个事件,如 RowChangedRowChangingRowDeletedRowDeleting 等,可以在数据发生变化时触发。

using System;
using System.Data;

class Program
{
    static void Main()
    {
        DataTable table = new DataTable("MyTable");
        table.Columns.Add("ID", typeof(int));
        table.Columns.Add("Name", typeof(string));
        table.Columns.Add("Age", typeof(int));

        // 订阅事件
        table.RowChanged += new DataRowChangeEventHandler(RowChangedEvent);

        DataRow row1 = table.NewRow();
        row1["ID"] = 1;
        row1["Name"] = "Alice";
        row1["Age"] = 25;
        table.Rows.Add(row1);
    }

    private static void RowChangedEvent(object sender, DataRowChangeEventArgs e)
    {
        Console.WriteLine($"Row changed: {e.Action}, {e.Row["Name"]}");
    }
}

12.使用 DataTable 的约束

我们可以为 DataTable 添加约束,如主键约束、唯一约束等。

using System;
using System.Data;

class Program
{
    static void Main()
    {
        DataTable table = new DataTable("MyTable");
        table.Columns.Add("ID", typeof(int));
        table.Columns.Add("Name", typeof(string));
        table.Columns.Add("Age", typeof(int));

        // 添加主键约束
        table.PrimaryKey = new DataColumn[] { table.Columns["ID"] };

        // 添加唯一约束
        table.Columns["Name"].Unique = true;

        DataRow row1 = table.NewRow();
        row1["ID"] = 1;
        row1["Name"] = "Alice";
        row1["Age"] = 25;
        table.Rows.Add(row1);

        // 尝试添加重复主键
        try
        {
            DataRow row2 = table.NewRow();
            row2["ID"] = 1; // 重复主键
            row2["Name"] = "Bob";
            row2["Age"] = 30;
            table.Rows.Add(row2);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }
}

13.使用 DataTable 的表达式列

我们可以使用表达式列来计算列的值。

using System;
using System.Data;

class Program
{
    static void Main()
    {
        DataTable table = new DataTable("MyTable");
        table.Columns.Add("ID", typeof(int));
        table.Columns.Add("Name", typeof(string));
        table.Columns.Add("Age", typeof(int));

        // 添加表达式列
        table.Columns.Add("IsAdult", typeof(bool), "Age >= 18");

        DataRow row1 = table.NewRow();
        row1["ID"] = 1;
        row1["Name"] = "Alice";
        row1["Age"] = 25;
        table.Rows.Add(row1);

        DataRow row2 = table.NewRow();
        row2["ID"] = 2;
        row2["Name"] = "Bob";
        row2["Age"] = 16;
        table.Rows.Add(row2);

        // 打印表达式列的值
        foreach (DataRow row in table.Rows)
        {
            Console.WriteLine($"{row["Name"]} is adult: {row["IsAdult"]}");
        }
    }
}

14.使用 DataTable 的 XML 序列化

我们可以将 DataTable 序列化为 XML,或者从 XML 反序列化为 DataTable

using System;
using System.Data;
using System.IO;

class Program
{
    static void Main()
    {
        DataTable table = new DataTable("MyTable");
        table.Columns.Add("ID", typeof(int));
        table.Columns.Add("Name", typeof(string));
        table.Columns.Add("Age", typeof(int));

        DataRow row1 = table.NewRow();
        row1["ID"] = 1;
        row1["Name"] = "Alice";
        row1["Age"] = 25;
        table.Rows.Add(row1);

        // 序列化为 XML
        string xml = table.GetXml();
        Console.WriteLine(xml);

        // 将 XML 保存到文件
        File.WriteAllText("table.xml", xml);

        // 从 XML 反序列化为 DataTable
        DataTable newTable = new DataTable();
        newTable.ReadXml("table.xml");

        // 打印反序列化后的行数据
        foreach (DataRow row in newTable.Rows)
        {
            Console.WriteLine($"{row["ID"]}, {row["Name"]}, {row["Age"]}");
        }
    }
}

15.使用 DataTable 的 JSON 序列化

我们可以使用 JsonConvert 类将 DataTable 序列化为 JSON,或者从 JSON 反序列化为 DataTable

using System;
using System.Data;
using Newtonsoft.Json;

class Program
{
    static void Main()
    {
        DataTable table = new DataTable("MyTable");
        table.Columns.Add("ID", typeof(int));
        table.Columns.Add("Name", typeof(string));
        table.Columns.Add("Age", typeof(int));

        DataRow row1 = table.NewRow();
        row1["ID"] = 1;
        row1["Name"] = "Alice";
        row1["Age"] = 25;
        table.Rows.Add(row1);

        // 序列化为 JSON
        string json = JsonConvert.SerializeObject(table);
        Console.WriteLine(json);

        // 从 JSON 反序列化为 DataTable
        DataTable newTable = JsonConvert.DeserializeObject<DataTable>(json);

        // 打印反序列化后的行数据
        foreach (DataRow row in newTable.Rows)
        {
            Console.WriteLine($"{row["ID"]}, {row["Name"]}, {row["Age"]}");
        }
    }
}

二、总结

DataTable 是 C# 中非常强大的数据结构,适用于处理内存中的数据。通过本教程,我们应该已经掌握了 DataTable 的基本操作,包括创建、添加、修改、删除、查询、排序、合并、克隆、复制、使用 DataView、事件处理、约束、表达式列、XML 和 JSON 序列化等操作。

风语者!平时喜欢研究各种技术,目前在从事后端开发工作,热爱生活、热爱工作。