目录
一、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 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);
                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 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 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 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 提供了多个事件,如 RowChanged, RowChanging, RowDeleted, RowDeleting 等,可以在数据发生变化时触发。
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);
                string xml = table.GetXml();        Console.WriteLine(xml);
                File.WriteAllText("table.xml", xml);
                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);
                string json = JsonConvert.SerializeObject(table);        Console.WriteLine(json);
                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 序列化等操作。
阅读原文:原文链接
该文章在 2025/10/18 11:19:15 编辑过