无法转换 IQueryable<> IOrderedQueryable 错误
我有以下 LINQ 代码:
var posts = (from p in db.Posts
.Include("Site")
.Include("PostStatus")
where p.Public == false
orderby p.PublicationTime
select p);
if (!chkShowIgnored.Checked) {
posts = posts.Where(p => p.PostStatus.Id != 90);
}
最后一行(额外的位置)给了我错误:
无法将类型“System.Linq.IQueryable”隐式转换为“System.Linq.IOrderedQueryable”。
我不确定这意味着什么...
为什么我会收到此错误?
一旦我将“orderby”子句添加到查询中,它就出现了,在此之前它编译得很好,所以我对正在发生的事情有一种预感,但我不能完全了解它。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尝试将
posts
专门声明为IQueryable
而不是var
(这将获取IOrderedQueryable
(它仍然会被排序)或者,重新构造它,以便我们在最后排序,允许我们(可选)在中间引入
where
:(显然,我们看一下
finalQuery
)它出错的原因是目前你(本质上)有:
Try declaring
posts
specifically asIQueryable<Post>
rather thanvar
(which will pick up theIOrderedQueryable<Post>
(it will still be ordered).Alternatively, re-structure it so we order at the end, allowing us to (optionally) bring in the
where
in the middle:(obviously, we look at
finalQuery
)The reason it is erroring is that currently you have (essentially):
lambda 表达式的结果是 IQueryable 类型。它不允许扩展方法Where,因此要首先使用它,您必须将其转换为例如列表。
你可以使用以下方法来做到这一点
The result of the lambda expressionis of type IQueryable. It doesn't allows the extension method Where, so to use it first you must convert this to, for example, a list.
You could do this using