Can this linq statement be refactored to return an IQueryable instead?
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 r开发者_运维问答est 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;
}
How about?
var queryable = source.AsQueryable();
return condition ? queryable.Where(predicate) : queryable;
Link
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.
精彩评论