我想将DataTable转换IEnumerable<>
为Dictionary
.我尝试了以下LINQ查询,
from DataRow row in ds.Tables[0].AsEnumerable() let rowDictionary = new Dictionary() from DataColumn column in row.Table.Columns.Cast () select rowDictionary.Add(column.ColumnName, row[column]).ToArray();
但是我收到以下错误:
error CS1943: An expression of type 'System.Collections.Generic.IEnumerable' is not allowed in a subsequent from clause in a query expression with source type 'System.Data.EnumerableRowCollection '. Type inference failed in the call to 'SelectMany'.
我知道我可以通过循环来强制执行此操作,但这似乎是我应该能够在LINQ中执行的操作.在此先感谢您的帮助!
我假设您想要的是每个行映射列的值为Dictionary:
var dt = new DataTable(); var columns = dt.Columns.Cast(); dt.AsEnumerable().Select(dataRow => columns.Select(column => new { Column = column.ColumnName, Value = dataRow[column] }) .ToDictionary(data => data.Column, data => data.Value));
这是我用Linq格式做的一种方式
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);