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

2

0

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.

Morrow answered 13/4, 2011 at 15:55 Comment(1)
You can indicate that Slauma provided the correct answer by clicking the checkmark next to his answer.Entrenchment
A
4

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

Aeriel answered 13/4, 2011 at 16:30 Comment(3)
Thank you very much I just had to use asMorrow
var qry = MyDataTable.AsEnumerable().AsQueryable() .Select("new(it[\"Country\"]) as CountryAlias");Morrow
Yes, I've also just seen that as is necessary. I'll edit my answer to correct that.Aeriel
T
0

I've used Slauma's answer and it worked. In addition i was doing OrderBy with dynamic linq maybe this will help to someone. I'll just drop the code here.

string dynamicLinqText = $"it[\"{sortColumnName}\"] {sortDirection}"; //it["PERSON_NAME"] asc
result = result.AsEnumerable().OrderBy(dynamicLinqText).CopyToDataTable();
Theirs answered 23/9, 2022 at 7:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.