I am using Linq to query my database and returning a generic IList.
Whatever I tried I couldn’t convert an IQueryable to an IList.
Here is my code.
I cannot write simpler than this and I don’t understand why it is not working.
public IList<IRegion> GetRegionList(string countryCode)
{
var query = from c in Database.RegionDataSource
where (c.CountryCode == countryCode)
orderby c.Name
select new {c.RegionCode, c.RegionName};
return query.Cast<IRegion>().ToList();
}
This returns an list with the right number of items but they are all empty
Please help, I am bloqued with this for a couple of days now
Your
selectstatement returns an anonymous type:new {c.RegionCode, c.RegionName}This can’t be converted to
IRegion– that would basically be Duck-typing, which C# doesn’t support.Your linq statement should return a type that implements
IRegion– then your code should work.However it shouldn’t run – the
Cast<IRegion>should throw a runtime exception.Basically:
Update
If the underlying Linq type implements
IRegionthis can be a lot simpler: