You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在C# .NET Core中如何将DataTable.Rows转换为Dictionary<T1,T2>列表

将DataTable转换为Dictionary列表的实现方法

给定如下演示DataTable:

var demoDatasets = new DataTable
{
  Columns = {
              { "ID", typeof(int) },
              { "Name", typeof(string) },
              { "Address", typeof(string) }
  },
  Rows = {
           { 1, "A", "AddressA1" },
           { 2, "B", "AddressB1" },
           { 3, "C", "AddressC1" }
         }
};

可以通过LINQ快速将其转换为List<Dictionary<string, object>>,每个Dictionary对应DataTable中的一行,键为列名,值为对应单元格的内容。

基础实现代码

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

// 执行转换
List<Dictionary<string, object>> dataList = demoDatasets.AsEnumerable()
    .Select(row => demoDatasets.Columns.Cast<DataColumn>()
        .ToDictionary(column => column.ColumnName, column => row[column]))
    .ToList();

代码说明

  • AsEnumerable():将DataTable转换为可枚举的DataRow集合,支持LINQ操作
  • Select():遍历每一行,将单个DataRow转换为Dictionary<string, object>
  • Columns.Cast<DataColumn>():将DataTable的列集合转换为强类型的DataColumn枚举,方便后续遍历
  • ToDictionary():以列名为键,行中对应列的值为值,生成单行对应的Dictionary
  • ToList():将所有行转换后的Dictionary收集为列表

处理DBNull值的健壮版本

如果DataTable中存在DBNull类型的空值,可以在转换时将其替换为null,避免后续处理异常:

List<Dictionary<string, object>> dataList = demoDatasets.AsEnumerable()
    .Select(row => demoDatasets.Columns.Cast<DataColumn>()
        .ToDictionary(column => column.ColumnName, 
                     column => row[column] == DBNull.Value ? null : row[column]))
    .ToList();

转换结果示例

转换后的dataList包含3个Dictionary元素,结构如下:

  • 第一个元素:{"ID": 1, "Name": "A", "Address": "AddressA1"}
  • 第二个元素:{"ID": 2, "Name": "B", "Address": "AddressB1"}
  • 第三个元素:{"ID": 3, "Name": "C", "Address": "AddressC1"}

内容的提问来源于stack exchange,提问作者Akter

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 22:30:57