IQueryable type to an Array

dynamic-linq iqueryable linq


I have a dynamic Linq query like this. I need to convert the result set into an array. But I am not able to convert the IQueryable type to an Array. Any suggestion?

my code:-

var query = Data.AsEnumerable()
                .Select("new(it[\"Country\"] as Country)", "it")

foreach (string str in query) // **getting error Unable to cast object of type 'DynamicClass1' to type 'System.String**


I fixed it using like this :- foreach(var str in query) .

But I have another issue now. I have added where condition to the query. Now i am getting error "No property or field 'Country' exists in type 'DataRow'". following is my query

 var query= Data.AsEnumerable().AsQueryable().Where("Country = @0", "London").Select("new (Country as Country)");
1/29/2014 5:36:19 AM

Accepted Answer

When you use Dynamic LINQ all extensions returns collection with dynamic elements, so you need change your code for example like this

foreach (dynamic str in query) 

also for your case str is object with field Country

for question from comment
if Data is DataTable when you call AsEnumerable or AsQueryable you work with collection of DataRow, so when you want filter it by column value you need use syntax for DataRow like this

Data.AsQueryable().Where("it[\"Country\"] = @0", "London")

or you can do select first like that

var query= Data.AsQueryable()
               .Select("new (it[\"Country\"] as Country)")
               .Where("Country = @0", "London")

until you don't specify type for field it can be Object so you need change Select clause like this

.Select("new(Convert.ToString(it[\"Country\"]) as Country)")

in this case when you call Where after Select field Country will is String, so String have Contains method

1/29/2014 6:56:06 AM

Related Questions

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow