nac*_*hid 16 c# linq ienumerable
我正在使用Linq查询我的数据库并返回一个通用的IList.
无论我尝试什么,我都无法将IQueryable转换为IList.
这是我的代码.
我不能写比这简单,我不明白为什么它不起作用.
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();
}
Run Code Online (Sandbox Code Playgroud)
这会返回一个包含正确数量的项目的列表,但它们都是空的请帮忙,我现在已经开了几天了
Kei*_*ith 16
您的select
语句返回匿名类型:new {c.RegionCode, c.RegionName}
这不能转换为IRegion
- 这基本上是鸭子打字,C#不支持.
你的linq语句应该返回一个实现的类型IRegion
- 然后你的代码应该工作.
但是它不应该运行 - Cast<IRegion>
应该抛出运行时异常.
基本上:
// 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();
}
Run Code Online (Sandbox Code Playgroud)
更新
如果底层的Linq类型实现了IRegion
这可以简单得多:
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();
}
Run Code Online (Sandbox Code Playgroud)
我很惊讶它不仅仅是完全失败 - 你试图将每个结果转换为一个IRegion
,但是你正在生成一个匿名类型的实例,这肯定不会实现IRegion
.
你有一个具体的具体类型IRegion
吗?