将一个动态数据表转换为一个List >(Turn a dynamic DataTable into a List>)

编程入门 行业动态 更新时间:2024-10-19 20:36:22
将一个动态数据表转换为一个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 ) )

更多推荐

本文发布于:2023-07-07 21:36:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1068501.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:转换为   数据表   动态   List   dynamic

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!