将一个动态数据表转换为一个List >(Turn a dynamic DataTable into a List>)
我想要一个优雅的方式来使用像这样的DataTable:
把它变成一个:
List<Dictionary<string,string>> values = dataTable.ToDictionary();列表中的每个字典都对应一行。 字典包含行的值,其中键是列名,值是列值。
该方法应该支持动态数量的列和名称。
I want an elegant way to take a DataTable like this one :
And turn it into a :
List<Dictionary<string,string>> values = dataTable.ToDictionary();Each dictionary in the list corresponds to a row. A dictionary contains the values of a row where the key is the column name and the value is the column value.
The method should support dynamic number of columns and names.
最满意答案
你需要把每一行变成一个字典:
// 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 ) )You need to turn each row into a dictionary:
// 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 ) )更多推荐
发布评论