New answers tagged

2

How about a generic extension method that takes a boolean and an expression, whereas the expression is only evaluated in case the boolean is true: public static IQueryable<T> When<T>( this IQueryable<T> source, bool trigger, Expression<Func<T, bool>> expression) { if (trigger) { return source.Where(...


5

I would further improve Henrik Hansen's code by throwing away the ifs and integrating the preconditions inside in the queries so they would become: yield articles.Where(article => !filters.IsAvailable.HasValue || article.IsAvailable == filters.IsAvailable); This would not only make it more readable but would show us that now we can actually generate ...


11

I read it as one long AND operation where the result is the articles that satisfy all the valid predicates. You could therefore build an enumerable of valid predicates in an extension method: public static class ArticleFilterExtensions { public static IEnumerable<Predicate<Article>> GetValidPredicates(this ArticleFiltersModel filter) ...


3

Given an extension method: public static IQueryable<T> NullWhere<T>(this IQueryable<T> source, Expression<Func<T, bool?>> expression, bool? compare) => compare.HasValue ? source.Where(Expression.Lambda<Func<T, bool>>(Expression.Equal(expression.Body, Expression.Constant((bool)compare)), expression.Parameters))...


Top 50 recent answers are included