Querying DataColumnCollection with LINQ

送分小仙女□ 提交于 2019-12-03 02:36:55

问题


I'm trying to perform a simple LINQ query on the Columns property of a DataTable:

from c in myDataTable.Columns.AsQueryable()
    select c.ColumnName

However, what I get is this:

Could not find an implementation of the query pattern for source type 'System.Linq.IQueryable'. 'Select' not found. Consider explicitly specifying the type of the range variable 'c'.

How can I get the DataColumnCollection to play nice with LINQ?


回答1:


How about:

var x = from c in dt.Columns.Cast<DataColumn>()
        select c.ColumnName;



回答2:


You could also use:

var x = from DataColumn c in myDataTable.Columns
        select c.ColumnName

It will effectively do the same as Dave's code: "in a query expression, an explicitly typed iteration variable translates to an invocation of Cast(IEnumerable)", according to the Enumerable.Cast<TResult> Method MSDN article.




回答3:


With Linq Method Syntax:

var x = myDataTable.Columns.Cast<DataColumn>().Select(c => c.ColumnName);


来源:https://stackoverflow.com/questions/237201/querying-datacolumncollection-with-linq

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!