Lance Collins
Lance Collins

Reputation: 3455

Returning an object from a LINQ query without casting it to a list

I have a LINQ query works when I set the return value to a List, however I just want to return an IQueryable<Post>. How would I do that?

public List<Post> GetPostByID(int id)
{
    var thePost = (from p in _context.Posts
                   where p.Id == id
                   select p).ToList();
    return thePost;
}

Upvotes: 1

Views: 111

Answers (2)

AdaTheDev
AdaTheDev

Reputation: 147374

 public IQueryable<Post> GetPostByID(int id)
 {
        return (from p in _context.Posts
                       where p.Id == id
                       select p);
 }

Naturally due to deferred execution, this query will be executed at the put the caller tries to enumerate the results.

Upvotes: 8

burning_LEGION
burning_LEGION

Reputation: 13460

var thePost = (from p in _context.Posts
                   where p.Id == id
                   select p);
    return thePost;

Upvotes: 1

Related Questions