gpt4 book ai didi

linq - 如何将 DataTable 转换为 IEnumerable>?

转载 作者:行者123 更新时间:2023-12-04 03:00:05 25 4
gpt4 key购买 nike

我想将 DataTable 转换为 IEnumerable<>Dictionary<string, object> .我尝试了以下 LINQ 查询,

from DataRow row in ds.Tables[0].AsEnumerable()
let rowDictionary = new Dictionary<string, object>()
from DataColumn column in row.Table.Columns.Cast<DataColumn>()
select rowDictionary.Add(column.ColumnName, row[column]).ToArray();

但我收到以下错误:
error CS1943: An expression of type 
'System.Collections.Generic.IEnumerable<System.Data.DataColumn>' is not
allowed in a subsequent from clause in a query expression with source type
'System.Data.EnumerableRowCollection<AnonymousType#1>'. Type inference
failed in the call to 'SelectMany'.

我知道我可以用循环来强制执行此操作,但这似乎是我应该能够在 LINQ 中执行的操作。在此先感谢您的帮助!

最佳答案

我假设您想要的是每个行映射列到值的字典:

var dt = new DataTable();

var columns = dt.Columns.Cast<DataColumn>();
dt.AsEnumerable().Select(dataRow => columns.Select(column =>
new { Column = column.ColumnName, Value = dataRow[column] })
.ToDictionary(data => data.Column, data => data.Value));

关于linq - 如何将 DataTable 转换为 IEnumerable<Dictionary<string, object>>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1633627/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com