您好,欢迎来到五一七教育网。
搜索
您的当前位置:首页C#基础:DataTable的基础用法

C#基础:DataTable的基础用法

来源:五一七教育网
// 示例:构建一个 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);

//获取相关数据:
Dictionary<string, string> columnTypeDictionary = res.Columns.Cast<DataColumn>().ToDictionary(col => col.ColumnName, col => col.DataType.ToString());
List<string> columnNames = columnTypeDictionary.Select(x=>x.Key).ToList();
List<string> columnTypes = columnTypeDictionary.Select(x=>x.Value).ToList();
Console.WriteLine($"数据条数: {res.Rows.Count}");
Console.WriteLine($"字段名: {string.Join(",", columnNames)}");
Console.WriteLine($"字段类型: {string.Join(",", columnTypes)}");
var dict = DtToDictionaryList(res);//数据内容字典(key=字段  value=字段对应的值)

public static List<Dictionary<string, string>> DtToDictionaryList(DataTable res)
{
    var list = new List<Dictionary<string, string>>();

    foreach (DataRow row in res.Rows)
    {
        var dict = new Dictionary<string, string>();

        foreach (DataColumn column in res.Columns)
        {
            dict[column.ColumnName] = row[column].ToString();
        }

        list.Add(dict);
    }

    return list;
}

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- 517ttc.cn 版权所有 赣ICP备2024042791号-8

违法及侵权请联系:TEL:199 18 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务