我正在使用 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();
}
这将返回一个包含正确数量项目的列表,但它们都是空的 请帮忙,我已经被这个困扰了几天了
最佳答案
你的 select
语句返回匿名类型:new {c.RegionCode, c.RegionName}
这不能转换为 IRegion
- 这基本上是 Duck-typing,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();
}
更新
如果底层 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();
}
关于c# - IEnumerable<> 到 IList<>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2728027/