Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
–
–
That's what
Expression.Invoke
is for.
Create a new lambda expression, and use
Expression.Invoke
on the original expression to compose the two expressions.
Sample:
Expression<Func<string, int>> inner = x => int.Parse(x);
var outer = Expression.Lambda<Func<int>>
(Expression.Invoke(inner, Expression.Constant("123")));
outer.Compile()().Dump(); // 123
Sadly, some expression parsers don't handle Invoke
correctly - they assume it to be an invocation of a method, and reject it. In that case, you need to inline the expression. That means visiting the whole inner expression and replacing the ParameterExpression
s with variables in the better case, or if parser doesn't support that either, inlining the argument in all the places.
Invoke the expression as Luaan suggested
Replace the parameters with the value you would like (a constant or a different expression)
Option 1 is as simple as Expression.Invoke
but may not be compatible with libraries such as LINQ. Option 2 is best done using an expression visitor:
private class ExchangeParametersVisitor : ExpressionVisitor
public ParameterExpression Parameter { get; set; }
public Expression Value { get; set; }
protected override Expression VisitParameter(ParameterExpression node)
if (node == Parameter)
return Value;
return node;
What you need to do is apply the visitor to the body of your lambda expression and use it to create a new lambda expression that contains all parameters as before except the one you replaced.
–
–
–
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.