title: Trouble combining Linq Expressions into a Func
body: <p>I've been trying to factor some common lambda subexpressions out into reusable components and have hit a wall.  I'll show what I've done so far with a simplified example and hope one of you can shed some light.</p>
  
  <p>My subexpressions are ultimately used in an NHibernate Query (IQueryable interface).  Here's an example:</p>
  
  <pre><code>var depts = session.Query&lt;Department&gt;().Where(d =&gt; d.employees.Any(ex1.AndAlso(ex2).Compile()));
  </code></pre>
  
  <p><strong>AndAlso</strong> is an <code>Expression</code> extension that's defined like this (taken from an answer to a related <strong>SO</strong> question, with some minor adjustments):</p>
  
  <pre><code>public class ParameterRebinder : ExpressionVisitor
  {
      private readonly Dictionary&lt;ParameterExpression, ParameterExpression&gt; _map;
  
      public ParameterRebinder(Dictionary&lt;ParameterExpression, ParameterExpression&gt; map)
      {
          _map = map ?? new Dictionary&lt;ParameterExpression, ParameterExpression&gt;();
      }
      public static Expression ReplaceParameters(Dictionary&lt;ParameterExpression, ParameterExpression&gt; map, Expression exp)
      {
          return new ParameterRebinder(map).Visit(exp);
      }
      protected override Expression VisitParameter(ParameterExpression p)
      {
          ParameterExpression replacement;
          if (_map.TryGetValue(p, out replacement))
          {
              p = replacement;
          }
          return base.VisitParameter(p);
      }
  }
  
  public static class ExpressionExtensions
  {
      public static Expression&lt;T&gt; Compose&lt;T&gt;(this Expression&lt;T&gt; first, Expression&lt;T&gt; second, Func&lt;Expression, Expression, Expression&gt; merge)
      {
          // build parameter map (from parameters of second to parameters of first)
          var map = first.Parameters.Select((f, i) =&gt; new { f, s = second.Parameters[i] }).ToDictionary(p =&gt; p.s, p =&gt; p.f);
          // replace parameters in the second lambda expression with parameters from the first
          var secondBody = ParameterRebinder.ReplaceParameters(map, second.Body);
          // apply composition of lambda expression bodies to parameters from the first expression 
          return Expression.Lambda&lt;T&gt;(merge(first.Body, secondBody), first.Parameters);
      }
      public static Expression&lt;Func&lt;T, bool&gt;&gt; AndAlso&lt;T&gt;(this Expression&lt;Func&lt;T, bool&gt;&gt; first, Expression&lt;Func&lt;T, bool&gt;&gt; second)
      {
          return first.Compose(second, Expression.AndAlso);
      }
      public static Expression&lt;Func&lt;T, bool&gt;&gt; OrElse&lt;T&gt;(this Expression&lt;Func&lt;T, bool&gt;&gt; first, Expression&lt;Func&lt;T, bool&gt;&gt; second)
      {
          return first.Compose(second, Expression.OrElse);
      }
  }
  </code></pre>
  
  <p>All would be well except that the <strong>Any</strong> call is an <code>IEnumerable</code> call, not an <code>IQueryable</code> call, so it expects a <code>Func</code> argument rather than an <code>Expression</code>.  To that end I call <code>Compile()</code> on the combined <code>Expression</code>, but then I get the following run-time error:</p>
  
  <blockquote>
    <p>Remotion.Linq.Parsing.ParserException: Could not parse expression
    'c.employees.Any(value(System.Func<code>2[Entities.Domain.Department,System.Boolean]))':
    Object of type 'System.Linq.Expressions.ConstantExpression' cannot be
    converted to type 'System.Linq.Expressions.LambdaExpression'. If you
    tried to pass a delegate instead of a LambdaExpression, this is not
    supported because delegates are not parsable expressions.
        at Remotion.Linq.Parsing.Structure.MethodCallExpressionParser.CreateExpressionNode(Type nodeType, MethodCallExpressionParseInfo parseInfo, Object[] additionalConstructorParameters)
    at
    Remotion.Linq.Parsing.Structure.MethodCallExpressionParser.Parse(String associatedIdentifier, IExpressionNode source, IEnumerable</code>1 arguments, MethodCallExpression expressionToParse)
    at
    Remotion.Linq.Parsing.Structure.ExpressionTreeParser.ParseMethodCallExpression(MethodCallExpression methodCallExpression, String associatedIdentifier)
    at
    Remotion.Linq.Parsing.Structure.QueryParser.GetParsedQuery(Expression expressionTreeRoot)
    at
    Remotion.Linq.Parsing.ExpressionTreeVisitors.SubQueryFindingExpressionTreeVisitor.VisitExpression(Expression expression)
    at
    Remotion.Linq.Parsing.ExpressionTreeVisitor.VisitLambdaExpression(LambdaExpression expression)
    at
    Remotion.Linq.Parsing.Structure.MethodCallExpressionParser.ProcessArgumentExpression(Expression argumentExpression)
    at System.Linq.Enumerable.WhereSelectEnumerableIterator<code>2.MoveNext()<br>
    at System.Linq.Buffer</code>1..ctor(IEnumerable<code>1 source)    at
    System.Linq.Enumerable.ToArray(IEnumerable</code>1 source)    at
    Remotion.Linq.Parsing.Structure.MethodCallExpressionParser.Parse(String associatedIdentifier, IExpressionNode source, IEnumerable`1 arguments, MethodCallExpression expressionToParse)
    at
    Remotion.Linq.Parsing.Structure.ExpressionTreeParser.ParseMethodCallExpression(MethodCallExpression methodCallExpression, String associatedIdentifier)
    at
    Remotion.Linq.Parsing.Structure.QueryParser.GetParsedQuery(Expression expressionTreeRoot)
    at NHibernate.Linq.NhRelinqQueryParser.Parse(Expression expression) in
    NhRelinqQueryParser.cs: line 39</p>
  </blockquote>
  
  <p>...and so on for the rest of the stack.</p>
  
  <p>My conundrum seems to be that one can't combine <code>Funcs</code>, only <code>Expressions</code> -- which produces another <code>Expression</code>.  But one can't hand an <code>Expression</code> to <code>IEnumerable.Any()</code> -- only a <code>Func</code>.  But then the <code>Func</code> produced by <code>Expression.Compile()</code> seems to be the wrong kind...</p>
  
  <p>Any ideas?</p>
  
  <p>Michael</p>