C#基础:DataTable的基础用法

一、代码 

using System;
using System.Collections.Generic;
using System.Data;

class Program
{
    static void Main()
    {
        // 示例:构建一个 DataTable
        DataTable res = new DataTable();
        res.Columns.Add("Id", typeof(int));
        res.Columns.Add("Name", typeof(string));
        res.Columns.Add("Age", typeof(int));

        res.Rows.Add(1, "John", 30);
        res.Rows.Add(2, "Alice", 25);
        res.Rows.Add(3, "Bob", 35);

        // 获取相关数据:
        var list = DtToDictionaryList(res);  // 获取包含元组的列表

        // 输出每行数据
        foreach (var tuple in list)
        {
            // 输出字段名称、字段类型和字段内容
            Console.WriteLine($"字段名称: {tuple.FieldName}, 字段类型: {tuple.FieldType}, 字段内容: {tuple.FieldValue}");
        }
    }

    // 返回每个列名、列类型和列值的元组列表
    public static List<(string FieldName, string FieldType, string FieldValue)> DtToDictionaryList(DataTable res)
    {
        var list = new List<(string FieldName, string FieldType, string FieldValue)>();

        // 遍历每行数据
        foreach (DataRow row in res.Rows)
        {
            // 遍历每列,获取字段名称、字段类型和字段值
            foreach (DataColumn column in res.Columns)
            {
                var fieldName = column.ColumnName;
                var fieldType = column.DataType.ToString();
                var fieldValue = row[column].ToString();

                // 添加元组到列表
                list.Add((fieldName, fieldType, fieldValue));
            }
        }

        return list;
    }
}

二、输出效果

字段名称: Id, 字段类型: System.Int32, 字段内容: 1
字段名称: Name, 字段类型: System.String, 字段内容: John
字段名称: Age, 字段类型: System.Int32, 字段内容: 30
字段名称: Id, 字段类型: System.Int32, 字段内容: 2
字段名称: Name, 字段类型: System.String, 字段内容: Alice
字段名称: Age, 字段类型: System.Int32, 字段内容: 25
字段名称: Id, 字段类型: System.Int32, 字段内容: 3
字段名称: Name, 字段类型: System.String, 字段内容: Bob
字段名称: Age, 字段类型: System.Int32, 字段内容: 35

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值