How to get an array in linq for an object?

var sites = from country in db.Countries select new SitiesViewByUser() { Country = country.Title, City = country.Cities .Select(m => m.Title).ToArray() }; 

City is an array string.

I need to get an array of Cities.Title

this code:

 foreach(var item in sites) 

get this error:

The LINQ to Entities expression does not recognize the method "System.String [] ToArray [String] (System.Collections.Generic.IEnumerable` 1 [System.String])", so it cannot be converted to an expression store.

0
source share
2 answers

You should be able to project an anonymous type, and then use ToArray() as soon as you return to Linq to land objects using AsEnumerable() :

 var sites = (from country in db.Countries select new { Country = country.Title, Cities = country.Cities.Select(m => m.Title) }) .AsEnumerable() .Select(country => new SitiesViewByUser() { Country = country.Title, City = country.Cities.ToArray() }; 

The problem is that ToArray() simply not defined for the Linq to Entities IQueryable (what would be the equivalent call in SQL?). Therefore, you have to capture your results, switch to Linq on objects, and then you can materialize them as needed.

+5
source

Use ToList() instead. You can specify the type of your ICollection<T> property, which represents a list of elements with a known amount.

ToList() was added for EF 6 in this work item http://entityframework.codeplex.com/workitem/808

0
source

All Articles