Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is my LINQ statement returning IEnumerable?

I have two very similar methods:

public IQueryable<User> Find(Func<User, bool> exp)
{
    return db.Users.Where(exp);
}

public IQueryable<User> All()
{
    return db.Users.Where(x => !x.deleted);
}

The top one, will not compile, saying it returns IEnumerable rather than IQueryable.

Why is this?

Also, I am aware I can add "AsQueryable()" on the end and it will work. What difference does that make though? Any performance hits? I understand that IQueryable has deferred execution and such, will I still get this benefit?

like image 816
Chris James Avatar asked Aug 21 '09 10:08

Chris James


1 Answers

Enumerable.Where takes Func<T, bool>.

Queryable.Where takes Expression<Func<T, bool>>.

You're calling Where with a Func<T, bool>, therefore only the Enumerable.Where call is applicable, and that returns IEnumerable<T>.

Change your method to:

public IQueryable<User> Find(Expression<Func<User, bool>> exp)
{
    return db.Users.Where(exp);
}

and it should be okay. Basically you want to pass in an expression tree instead of a delegate, so that the expression can be converted to SQL.

like image 134
Jon Skeet Avatar answered Sep 19 '22 21:09

Jon Skeet