开发者

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.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜