using System;
using System.Data;
class Program
{
static void Main()
{
// 创建一个 DataTable 并添加一些数据
DataTable dt = new DataTable();
dt.Columns.Add("ID", typeof(int));
dt.Columns.Add("Name", typeof(string));
dt.Rows.Add(1, "Alice");
dt.Rows.Add(2, "Bob");
dt.Rows.Add(3, "Charlie");
// 遍历 DataTable 的方法一:使用 foreach 循环
Console.WriteLine("方法一:使用 foreach 循环遍历 DataTable");
foreach (DataRow row in dt.Rows)
{
Console.WriteLine($"ID: {row["ID"]}, Name: {row["Name"]}");
}
// 遍历 DataTable 的方法二:使用 for 循环和 Rows.Count
Console.WriteLine("\n方法二:使用 for 循环和 Rows.Count 遍历 DataTable");
for (int i = 0; i < dt.Rows.Count; i++)
{
Console.WriteLine($"ID: {dt.Rows[i]["ID"]}, Name: {dt.Rows[i]["Name"]}");
}
}
}
创建 DataTable:
DataTable 类创建一个新的表格,并通过 Columns.Add 方法添加列。Rows.Add 方法向表格中添加行。遍历 DataTable:
foreach 循环遍历 DataTable.Rows 集合。每一行都是一个 DataRow 对象,可以通过索引访问列的值。for 循环和 Rows.Count 属性遍历 DataTable.Rows 集合。这种方式适用于需要知道当前行索引的情况。这两种方法都可以有效地遍历 DataTable 中的所有行,并根据需要处理每一行的数据。
上一篇:c# 字符串反转
下一篇:c# predicate
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站