Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Basically you need to re-write one of the trees, so that you can combine the expressions. Fortunately <code>ExpressionVisitor</code> helps us:</p> <pre><code>static void Main() { Expression&lt;Func&lt;object, bool&gt;&gt; exp1 = x =&gt; ((string)x).StartsWith("a"); Expression&lt;Func&lt;object, bool&gt;&gt; exp2 = y =&gt; ((string)y).StartsWith("b"); // the two expressions here are purely for illustration var exp3 = Combine(exp1, exp2, Expression.OrElse); // i.e. || var exp4 = Combine(exp1, exp2, Expression.AndAlso); // i.e. &amp;&amp; } static Expression&lt;Func&lt;TValue, TResult&gt;&gt; Combine&lt;TValue, TResult&gt;( Expression&lt;Func&lt;TValue, TResult&gt;&gt; left, Expression&lt;Func&lt;TValue, TResult&gt;&gt; right, Func&lt;Expression, Expression, BinaryExpression&gt; combination) { // rewrite the body of "right" using "left"'s parameter in place // of the original "right"'s parameter var newRight = new SwapVisitor(right.Parameters[0], left.Parameters[0]) .Visit(right.Body); // combine via &amp;&amp; / || etc and create a new lambda return Expression.Lambda&lt;Func&lt;TValue, TResult&gt;&gt;( combination(left.Body, newRight), left.Parameters); } class SwapVisitor : ExpressionVisitor { private readonly Expression from, to; public SwapVisitor(Expression from, Expression to) { this.from = from; this.to = to; } public override Expression Visit(Expression node) { return node == from ? to : base.Visit(node); } } </code></pre> <p>Note that this also allows other arbitrary uses, for example:</p> <pre><code>Expression&lt;Func&lt;object, int&gt;&gt; exp1 = x =&gt; x.GetHashCode(); Expression&lt;Func&lt;object, int&gt;&gt; exp2 = y =&gt; y.ToString().Length; var exp3 = Combine(exp1, exp2, Expression.Add); // which is: x =&gt; x.GetHashCode() + x.ToString().Length; </code></pre> <p>I can think of no <em>practical</em> use for that ... but it is there ;p</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