C# DataTable 教學

一、DataTable 基本使用

1. 建立 DataTable

using System;
using System.Data;

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

        // 新增欄位(資料欄)
        table.Columns.Add("ID", typeof(int));
        table.Columns.Add("Name", typeof(string));
        table.Columns.Add("Age", typeof(int));

        Console.WriteLine("DataTable 已建立。");
    }
}

2. 新增資料列

// 新增一筆資料列
DataRow row = table.NewRow();
row["ID"] = 1;
row["Name"] = "John";
row["Age"] = 18;
table.Rows.Add(row);

// 直接新增另一筆資料
table.Rows.Add(2, "Jane", 19);

Console.WriteLine("已新增資料列。");

3. 瀏覽 DataTable 資料

// 顯示所有資料
foreach (DataRow r in table.Rows)
{
    Console.WriteLine($"ID: {r["ID"]}, Name: {r["Name"]}, Age: {r["Age"]}");
}

二、DataTable 資料操作

1. 查詢資料 (Select)

// 查詢年齡大於 18 的學生
DataRow[] result = table.Select("Age > 18");
Console.WriteLine("\n查詢結果:");
foreach (DataRow r in result)
{
    Console.WriteLine($"ID: {r["ID"]}, Name: {r["Name"]}, Age: {r["Age"]}");
}

2. 修改資料

// 修改第一筆資料的名稱
table.Rows[0]["Name"] = "John Doe";

3. 刪除資料

// 刪除符合條件的資料
DataRow[] rowsToDelete = table.Select("Age < 19");
foreach (DataRow r in rowsToDelete)
{
    table.Rows.Remove(r);
}

4. 排序與篩選

// 排序:依年齡遞增排序
DataView view = table.DefaultView;
view.Sort = "Age ASC";
DataTable sortedTable = view.ToTable();

5. DataTable 與 DataSet 轉換

// 建立 DataSet
DataSet dataSet = new DataSet();
dataSet.Tables.Add(table);

// 從 DataSet 取得 DataTable
DataTable retrievedTable = dataSet.Tables["Students"];

6. 將 DataTable 轉換為 CSV

using System.IO;
using System.Text;

static void ExportToCSV(DataTable table, string filePath)
{
    StringBuilder sb = new StringBuilder();
    string[] columnNames = table.Columns.Cast<DataColumn>().Select(column => column.ColumnName).ToArray();
    sb.AppendLine(string.Join(",", columnNames));

    foreach (DataRow row in table.Rows)
    {
        string[] fields = row.ItemArray.Select(field => field.ToString()).ToArray();
        sb.AppendLine(string.Join(",", fields));
    }

    File.WriteAllText(filePath, sb.ToString());
}
Last modification:May 13, 2025
If you think my article is useful to you, please feel free to appreciate