Note that there are some explanatory texts on larger screens.

plurals
  1. POLinq PredicateBuilder with conditional AND, OR and NOT filters
    text
    copied!<p>We have a project using LINQ to SQL, for which I need to rewrite a couple of search pages to allow the client to select whether they wish to perform an <em>and</em> or an <em>or</em> search.</p> <p>I though about redoing the LINQ queries using <a href="http://www.albahari.com/nutshell/predicatebuilder.aspx" rel="noreferrer">PredicateBuilder</a> and have got this working pretty well I think. I effectively have a class containing my predicates, e.g.:</p> <pre><code>internal static Expression&lt;Func&lt;Job, bool&gt;&gt; Description(string term) { return p =&gt; p.Description.Contains(term); } </code></pre> <p>To perform the search i'm doing this (some code omitted for brevity):</p> <pre><code>public Expression&lt;Func&lt;Job, bool&gt;&gt; ToLinqExpression() { var predicates = new List&lt;Expression&lt;Func&lt;Job, bool&gt;&gt;&gt;(); // build up predicates here if (SearchType == SearchType.And) { query = PredicateBuilder.True&lt;Job&gt;(); } else { query = PredicateBuilder.False&lt;Job&gt;(); } foreach (var predicate in predicates) { if (SearchType == SearchType.And) { query = query.And(predicate); } else { query = query.Or(predicate); } } return query; } </code></pre> <p>While i'm reasonably happy with this, I have two concerns:</p> <ol> <li>The if/else blocks that evaluate a SearchType property feel like they could be a potential code smell.</li> <li>The client is now insisting on being able to perform 'and not' / 'or not' searches.</li> </ol> <p>To address point 2, I think I could do this by simply rewriting my expressions, e.g.:</p> <pre><code>internal static Expression&lt;Func&lt;Job, bool&gt;&gt; Description(string term, bool invert) { if (invert) { return p =&gt; !p.Description.Contains(term); } else { return p =&gt; p.Description.Contains(term); } } </code></pre> <p>However this feels like a bit of a kludge, which usually means there's a better solution out there. Can anyone recommend how this could be improved? I'm aware of dynamic LINQ, but I don't really want to lose LINQ's strong typing.</p>
 

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