Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You could use PredicateBuilder from <a href="http://www.albahari.com/nutshell/linqkit.aspx" rel="nofollow">LinqKit</a>. It adds some new extension methods to predicate lambdas:</p> <pre><code>var predicate = PredicateBuilder.True&lt;Customer&gt;(); if (searchingFirstName) { predicate = predicate.And(cust =&gt; cust.First == firstName); } if (searchingOrders) { // Some code to unify the .And() and .Or() cases Expression&lt;Func&lt;Order, bool&gt;&gt; subpredicate; Func&lt;Expression&lt;Func&lt;Order, bool&gt;&gt;, Expression&lt;Func&lt;Order, bool&gt;&gt;, Expression&lt;Func&lt;Order, bool&gt;&gt;&gt; joiner; if (orderMethodAny) { subpredicate = PredicateBuilder.True&lt;Order&gt;(); joiner = PredicateBuilder.And; } else { subpredicate = PredicateBuilder.False&lt;Order&gt;(); joiner = PredicateBuilder.Or; } if (searchingOrderDate) { // ... } if (searchingOrderWeight) { switch (orderOp) { case Op.Less: subpredicate = joiner(subpredicate, ord =&gt; ord.Weight &lt; orderWeight); break; case Op.LessEqual: subpredicate = joiner(subpredicate, ord =&gt; ord.Weight &lt;= orderWeight); break; case Op.Equal: subpredicate = joiner(subpredicate, ord =&gt; ord.Weight == orderWeight); break; case Op.GreaterEqual: subpredicate = joiner(subpredicate, ord =&gt; ord.Weight &gt;= orderWeight); break; case Op.Greater: subpredicate = joiner(subpredicate, ord =&gt; ord.Weight &gt; orderWeight); break; case Op.NotEqual: subpredicate = joiner(subpredicate, ord =&gt; ord.Weight != orderWeight); break; } } if (searchingOrderQuantity) { // ... } if (searchingOrderItemName) { // ... } if (searchingOrderPrice) { // ... } predicate = predicate.And(cust =&gt; cust.Orders.Any(subpredicate)); } if (searchingZipCode) { predicate = predicate.And(cust =&gt; cust.ZipCode == zipCode); } var query = Context.Customers.Where(predicate); </code></pre> <p>You might need to call <code>.Expand()</code> on the predicates before passing them as arguments, or <code>.AsExpandable()</code> on the queryable, if you are using the Entity Framework.</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