tags:

views:

50

answers:

2

Hi folks,

i have the following linq extension method, which returns an IEnumerable. This means, that this piece of code ends up hitting the DB, before the rest of the linq statement has been finished.

Is it possible to refactor this so it returns an IQueryable instead?

public static IEnumerable<TSource> WhereIf<TSource>
    (this IEnumerable<TSource> source, bool condition, 
     Func<TSource, bool> predicate)
{
    return condition ? source.Where(predicate) : source;
}
+1  A: 

How about?

var queryable = source.AsQueryable();
return condition ? queryable.Where(predicate) : queryable;

Link

Josh Einstein
A: 

How about the following:

public static IQueryable<TSource> WhereIf<TSource>
    (this IQueryable<TSource> source, bool condition, 
     Func<TSource, bool> predicate)
{
    return condition ? source.Where(predicate) : source;
}

If you change IEnumerable to IQueryable, then source.Where would also return an IQueryable when called, and seeing as source itself would be an IQueryable, the whole return statement would succeed in either case.

jrista
Error: Cannot implicitly convert type 'System.Collections.Generic.IEnumerable<T>' to 'System.Linq.IQueryable<T>'. An explicit conversion exists (are you missing a cast?)
Pure.Krome
Where exactly do you get that exception? Given that the above is an extension method, if 'source' is not an IQueryable<T> already, you shouldn't be able to call the method in the first place...
jrista
compile error, not exception.
Pure.Krome
Well, not sure why it won't compile. If you have an IQueryable<T>, you should be able to use it with an extension method that works with and returns IQueryable<T> rather than IEnumerable<T>, and delay execution against a database.
jrista