如何将DataTable转换为IEnumerable <dictionary <string,object =“”>&gt;?</dictionary <string,>

时间:2009-10-27 20:56:50

标签: linq datatable

我想将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中执行的操作。在此先感谢您的帮助!

3 个答案:

答案 0 :(得分:10)

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

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

答案 1 :(得分:7)

这是我用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);

答案 2 :(得分:4)

为什么不能更简单,因为你有linq?

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

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

如果您正在使用强类型数据集,那就更容易了:

var dt = new dsData.UsersDataTable();

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