Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

c# 遍历datatable

作者:浪子无家   发布日期:2026-04-17   浏览:3

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"]}");
        }
    }
}

解释说明:

  1. 创建 DataTable

    • 使用 DataTable 类创建一个新的表格,并通过 Columns.Add 方法添加列。
    • 使用 Rows.Add 方法向表格中添加行。
  2. 遍历 DataTable

    • 方法一:使用 foreach 循环遍历 DataTable.Rows 集合。每一行都是一个 DataRow 对象,可以通过索引访问列的值。
    • 方法二:使用 for 循环和 Rows.Count 属性遍历 DataTable.Rows 集合。这种方式适用于需要知道当前行索引的情况。

这两种方法都可以有效地遍历 DataTable 中的所有行,并根据需要处理每一行的数据。

上一篇:c# 字符串反转

下一篇:c# predicate

大家都在看

c# 二进制

c# 创建目录

c# datatable group by

c# tcp client

c# type.gettype

c# sqlconnection

c# string.format 小数位数

.net和c#

c#获取系统时间

c#游戏开发

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站