C# 将动态数据表转换为列表<;字典<;字符串,字符串>&燃气轮机;

C# 将动态数据表转换为列表<;字典<;字符串,字符串>&燃气轮机;,c#,dictionary,datatable,todictionary,C#,Dictionary,Datatable,Todictionary,我想要一种优雅的方式来获取这样一个数据表: 把它变成一个: List<Dictionary<string,string>> values = dataTable.ToDictionary(); List values=dataTable.ToDictionary(); 列表中的每个词典对应一行。字典包含一行的值,其中键是列名,值是列值 该方法应支持动态的列数和名称。您需要将每一行转换为字典: // Iterate through the rows... table.

我想要一种优雅的方式来获取这样一个数据表:

把它变成一个:

List<Dictionary<string,string>> values = dataTable.ToDictionary();
List values=dataTable.ToDictionary();
列表中的每个词典对应一行。字典包含一行的值,其中键是列名,值是列值


该方法应支持动态的列数和名称。

您需要将每一行转换为字典:

// Iterate through the rows...
table.AsEnumerable().Select(
    // ...then iterate through the columns...
    row => table.Columns.Cast<DataColumn>().ToDictionary(
        // ...and find the key value pairs for the dictionary
        column => column.ColumnName,    // Key
        column => row[column] as string // Value
    )
)
//遍历行。。。
table.AsEnumerable()。选择(
//…然后遍历列。。。
行=>table.Columns.Cast().ToDictionary(
//…并找到字典的键值对
column=>column.ColumnName,//键
column=>行[column]作为字符串//值
)
)

回答得很好!真的帮我完成了我的项目。