Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>So what you're looking for is an implementation of a predicate builder that can take any number of expressions and OR them together. Here is an implementation that will work with any query provider:</p> <pre><code>public static class PredicateBuilder { public static Expression&lt;Func&lt;T, bool&gt;&gt; True&lt;T&gt;() { return f =&gt; true; } public static Expression&lt;Func&lt;T, bool&gt;&gt; False&lt;T&gt;() { return f =&gt; false; } public static Expression&lt;Func&lt;T, bool&gt;&gt; Or&lt;T&gt;( this Expression&lt;Func&lt;T, bool&gt;&gt; expr1, Expression&lt;Func&lt;T, bool&gt;&gt; expr2) { var secondBody = expr2.Body.Replace(expr2.Parameters[0], expr1.Parameters[0]); return Expression.Lambda&lt;Func&lt;T, bool&gt;&gt; (Expression.OrElse(expr1.Body, secondBody), expr1.Parameters); } public static Expression&lt;Func&lt;T, bool&gt;&gt; And&lt;T&gt;( this Expression&lt;Func&lt;T, bool&gt;&gt; expr1, Expression&lt;Func&lt;T, bool&gt;&gt; expr2) { var secondBody = expr2.Body.Replace(expr2.Parameters[0], expr1.Parameters[0]); return Expression.Lambda&lt;Func&lt;T, bool&gt;&gt; (Expression.AndAlso(expr1.Body, secondBody), expr1.Parameters); } } </code></pre> <p>which uses:</p> <pre><code>internal class ReplaceVisitor : ExpressionVisitor { private readonly Expression from, to; public ReplaceVisitor(Expression from, Expression to) { this.from = from; this.to = to; } public override Expression Visit(Expression node) { return node == from ? to : base.Visit(node); } } public static Expression Replace(this Expression expression, Expression searchEx, Expression replaceEx) { return new ReplaceVisitor(searchEx, replaceEx).Visit(expression); } </code></pre> <p>This allows you to take any two expressions and create a new expression that is the result of ORing them together.</p> <pre><code>List&lt;Tuple&lt;string, string&gt;&gt; list = CreateList(); var finalExpression = list.Aggregate(PredicateBuilder.False&lt;Data&gt;(), (predicate, pair) =&gt; predicate.Or(n =&gt; n.Item1 == pair.Item2)); var query = data.Where(finalExpression); </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload