开发者

Cannot convert IQueryable<> to IOrderedQueryable error

开发者 https://www.devze.com 2022-12-11 23:17 出处:网络
I have the following LINQ code: var posts = (from p in db.Posts .Include(\"Site\") .Include(\"PostStatus\")

I have the following LINQ code:

    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);
        }

That last line (the extra where) is giving me the error:

Cannot implicitly convert type 'System.Linq.IQueryable' to 'System.Linq.IOrderedQueryable'.

I'm not sure what this means...

Why am I getting this error?

It appeared once I added the "orderby" clause to the query, before that it compiled fine, so I have kind of a hunch of what is going on, but I can't quite put my finger into it.


Try declaring posts specifically as IQueryable<Post> rather than var (which will pick up the IOrderedQueryable<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:

var posts = from p in db.Posts
             .Include("Site")
             .Include("PostStatus")
            where p.Public == false
            select p);

if (!chkShowIgnored.Checked) {
    posts = posts.Where(p => p.PostStatus.Id != 90);
}
var finalQuery = posts.OrderBy(p => p.PublicationTime);

(obviously, we look at finalQuery)

The reason it is erroring is that currently you have (essentially):

IOrderedQueryable<Post> posts = {snip};
...
posts = {something (Where) that returns IQueryable<Post>}


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

posts = posts.ToList().Where(p => p.PostStatus.Id != 90);
0

精彩评论

暂无评论...
验证码 换一张
取 消