IEnumerable<> to IList<>
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 select
statement 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:
// this isn't anonymous, and should cast
public class MyRegion : IRegion {
public string RegionCode {get;set;}
public string RegionName {get;set;}
}
public IList<IRegion> GetRegionList(string countryCode)
{
var query = from c in Database.RegionDataSource
where (c.CountryCode == countryCode)
orderby c.Name
select new MyRegion {RegionCode = c.RegionCode, RegionName = c.RegionName};
return query.Cast<IRegion>().ToList();
}
Update
If the underlying Linq type implements IRegion
this can be a lot simpler:
public IList<IRegion> GetRegionList(string countryCode)
{
var query =
from region in Database.RegionDataSource
where region.CountryCode == countryCode
orderby region.Name
select region;
return query.ToList();
}
I'm surprised it's not just failing completely - you're trying to cast each result to an IRegion
, but you're generating instances of an anonymous type, which certainly won't implement IRegion
.
Do you have a concrete type which implements IRegion
?
The cast to IRegion
won't work. You're selecting an anonymous type that won't implement IRegion
. Is there a way you can create an instance of something that implements IRegion?
Maybe you need something like this:
public IList<IRegion> GetRegionList(string countryCode)
{
var query = from c in Database.RegionDataSource
where (c.CountryCode == countryCode)
orderby c.Name
select new Region()
{
RegionCode = c.RegionCode,
RegionName = c.RegionName
};
return query.ToList();
}
Maybe you need something like this:
public IList<IRegion> GetRegionList(string countryCode)
{
var query = from c in Database.RegionDataSource
where (c.CountryCode == countryCode)
orderby c.Name
select new Region()
{
RegionCode = c.RegionCode,
RegionName = c.RegionName
};
return query.ToList();
}
精彩评论