title: How do I dynamically create an Expression<Func<MyClass, bool>> predicate from Expression<Func<MyClass, string>>?
body: <p>I trying to append where predicates and my goal is to create the same expression as:</p>
  
  <pre><code>Services.Where(s =&gt; s.Name == "Modules" &amp;&amp; s.Namespace == "Namespace");
  </code></pre>
  
  <p>I have the following code:</p>
  
  <pre><code>Expression&lt;Func&lt;Service,string&gt;&gt; sel1 = s =&gt; s.Name;
  Expression&lt;Func&lt;Service,string&gt;&gt; sel2 = s =&gt; s.Namespace;
  
  var val1 = Expression.Constant("Modules");
  var val2 = Expression.Constant("Namespace");
  
  Expression e1 = Expression.Equal(sel1.Body, val1);
  Expression e2 = Expression.Equal(sel2.Body, val2);
  var andExp = Expression.AndAlso(e1, e2);
  
  ParameterExpression argParam = Expression.Parameter(typeof(string), "s");
  var lambda = Expression.Lambda&lt;Func&lt;string, bool&gt;&gt;(andExp, argParam);
  </code></pre>
  
  <p>This create the following output:</p>
  
  <pre><code>s =&gt; ((s.Name == "Modules") AndAlso (s.Namespace == "Namespace"))
  </code></pre>
  
  <p>However, this is faulty since the parameter for <strong>Name</strong> and <strong>Namespace</strong> isn't the same. If I change one of the expression selector to:</p>
  
  <pre><code>Expression&lt;Func&lt;Service,string&gt;&gt; sel2 = srv =&gt; srv.Namespace;
  </code></pre>
  
  <p>The output will be:</p>
  
  <pre><code>s =&gt; ((s.Name == "Modules") AndAlso (srv.Namespace == "Namespace"))
  </code></pre>
  
  <p>How can I create a valid expression with use of <strong>sel1</strong> and <strong>sel2</strong>?</p>
  
  <p><strong>UPDATE (28 feb 2011)</strong></p>
  
  <p>I solved it by creating invoke expressions: <code>Expression.Invoke</code> so the lambda expressions sel1 and sel2 don't necessary need to be a MemberExpression:</p>
  
  <pre><code>Expression&lt;Func&lt;Service,string&gt;&gt; sel1 = s =&gt; s.Name;
  Expression&lt;Func&lt;Service,string&gt;&gt; sel2 = srv =&gt; srv.Namespace;
  
  var val1 = Expression.Constant("Modules");
  var val2 = Expression.Constant("Namespace");
  
  Expression&lt;Func&lt;Service, bool&gt;&gt; lambda = m =&gt; true;
  var modelParameter = lambda.Parameters.First();
  
  // sel1 predicate
  {
      var invokedExpr = Expression.Invoke(sel1, modelParameter);
      var binaryExpression = Expression.Equal(invokedExpr, val1);
      lambda = Expression.Lambda&lt;Func&lt;Service, bool&gt;&gt;(Expression.AndAlso(binaryExpression, lambda.Body), lambda.Parameters);
  }
  // sel2 predicate
  {
      var invokedExpr = Expression.Invoke(sel2, modelParameter);
      var binaryExpression = Expression.Equal(invokedExpr, val2);
      lambda = Expression.Lambda&lt;Func&lt;Service, bool&gt;&gt;(Expression.AndAlso(binaryExpression, lambda.Body), lambda.Parameters);
  }
  </code></pre>