title: Local variable and expression trees
body: <p>I am learning expression trees in C#.</p>
  
  <p>I am stuck now for a while:</p>
  
  <pre><code>string filterString = "ruby";
  Expression&lt;Func&lt;string, bool&gt;&gt; expression = x =&gt; x == filterString;
  </code></pre>
  
  <p>How can I construct this expression by code? There is no sample how to capture a local variable. This one is easy:</p>
  
  <pre><code>Expression&lt;Func&lt;string, bool&gt;&gt; expression = x =&gt; x == "ruby";
  </code></pre>
  
  <p>This would be:</p>
  
  <pre><code>ParameterExpression stringParam = Expression.Parameter(typeof(string), "x");
  Expression constant = Expression.Constant("ruby");
  BinaryExpression equals = Expression.Equal(stringParam, constant);
  Expression&lt;Func&lt;string, bool&gt;&gt; lambda1 =
      Expression.Lambda&lt;Func&lt;string, bool&gt;&gt;(
          equals,
          new ParameterExpression[] { stringParam });
  </code></pre>
  
  <p>The debugger prints the following for (x => x == filterString) :</p>
  
  <blockquote>
    <p>{x => (x ==
    value(Predicate.Program+&lt;>c__DisplayClass3).filterString)}</p>
  </blockquote>
  
  <p>Thanks for shedding some light on this topic.</p>