Dynamic Linq - no property or field exists in type 'datarow'

谁说胖子不能爱 提交于 2019-12-01 13:01:13

问题


I am using Northwind Customers Table where I fill the dataset and get the datatable.

I am trying to use dynamic linq and want to select columnName dynamically

var qry = MyDataTable.AsEnumerable().AsQueryable().Select("new(Country)");

Right now I have hard coded country but even then I get this error

No property or field 'Country' exists in type 'datarow'

I would like to eventually change this query to take the column name dynamically.

Please help!!! thanks.


回答1:


The important hint is here (in bold):

No property or field 'Country' exists in type 'datarow'

The extension method AsEnumerable of the DataTable class returns an IEnumerable<T> where T has the type DataRow. Now the Select method of Dynamic LINQ wants to work with this type DataRow which hasn't a property Country of course.

You could try this instead:

var qry = MyDataTable.AsEnumerable().AsQueryable()
    .Select("new(it[\"Country\"] as CountryAlias)");

it now represents a variable of type DataRow and you can use methods of this type and perhaps also the indexer in my example above. (Dynamic LINQ supports accessing array elements by an integer index, but I am not sure though if accessing an indexer with a string key will work.)



来源:https://stackoverflow.com/questions/5652096/dynamic-linq-no-property-or-field-exists-in-type-datarow

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