开发者

How can I convert a DataTable to an IEnumerable<Dictionary<string, object>>?

开发者 https://www.devze.com 2022-12-10 02:43 出处:网络
I\'d like to convert a DataTable to an IEnumerable<> of Dictionary<string, object>.I tried the following LINQ query,

I'd like to convert a DataTable to an IEnumerable<> of Dictionary<string, object>. I tried the following LINQ query,

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();

but I get the following error:

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'.

I kn开发者_运维百科ow I can brute-force this with a loop, but it seems like something I should be able to do in LINQ. Thanks in advance for any help!


I assume that what you want is a Dictionary for each row mapping column to value:

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));


Here is a way I do it in the Linq format

       var registerdataVerify = (from o in dt.AsEnumerable()
                                  select new
                                  {                                         
                                      DataDef =o["shortName"].ToString(),
                                      Value = Convert.ToInt32(o["valueDec"])
                                  }).ToDictionary(n => n.DataDef, n => n.Value);


Why not something simpler since you have linq?

var dt = new DataTable();
var columnIndex = 0;
var columnName = "UserID";

var Dict = dt.AsEnumerable().ToDictionary( _
           row => row(columnName), _
           row => row(columnIndex));

It becomes even easier if you're working with strongly-typed datasets:

var dt = new dsData.UsersDataTable();

var Dict = dt.ToDictionary(dr => dr.UserName, dr => dr.UserID);
0

精彩评论

暂无评论...
验证码 换一张
取 消