Combine Lambda Expressions

后端 未结 3 765
别那么骄傲
别那么骄傲 2020-12-06 02:31

I am looking for a way to combine two lambda expressions, without using an Expression.Invoke on either expression. I want to essentially build a new expression

3条回答
  •  半阙折子戏
    2020-12-06 03:11

    Your solution seems to be narrowly tailored to your specific problem, which seems inflexible.

    It seems to me that you could solve your problem straightforwardly enough through simple lambda substitution: replace instances of the parameter (or "free variable" as they call it in lambda calculus) with the body. (See Marc's answer for some code to do so.)

    Since parameter in expression trees have referential identity rather than value identity there isn't even a need to alpha rename them.

    That is, you have:

    Expression> ab = a => f(a);  // could be *any* expression using a
    Expression> bc = b => g(b);  // could be *any* expression using b
    

    and you wish to produce the composition

    Expression> ac = a => g(f(a)); // replace all b with f(a).
    

    So take the body g(b), do a search-and-replace visitor looking for the ParameterExpression for b, and replace it with the body f(a) to give you the new body g(f(a)). Then make a new lambda with the parameter a that has that body.

提交回复
热议问题