There is nothing out of the box, but you can create your own tool to provide this functionality.
You can write a method that takes an expression that has two parameters, one βrealβ parameter and one parameter of some value that you want to replace with the value of another expression. Then you can have an expression that resolves this value and replaces all instances of the parameter with a second expression:
public static Expression<Func<TSource, TResult>> BuildExpression <TSource, TOther, TResult>( Expression<Func<TSource, TOther, TResult>> function, Expression<Func<TOther>> innerExpression) { var body = function.Body.Replace(function.Parameters[1], innerExpression.Body); return Expression.Lambda<Func<TSource, TResult>>(body, function.Parameters[0]); }
You can use the following method to replace all instances of one expression with another:
public static Expression Replace(this Expression expression, Expression searchEx, Expression replaceEx) { return new ReplaceVisitor(searchEx, replaceEx).Visit(expression); } internal class ReplaceVisitor : ExpressionVisitor { private readonly Expression from, to; public ReplaceVisitor(Expression from, Expression to) { this.from = from; this.to = to; } public override Expression Visit(Expression node) { return node == from ? to : base.Visit(node); } }
Then you can apply it to your case as follows:
public static Expression<Func<int, int>> Add(Expression<Func<int>> expr) { return BuildExpression((int i, int n) => i + n, expr); }
Servy source share