Search code examples
c#asp.net-mvclambdaexpression-trees

How do I create a lambda expression of type Expression.Lambda<Action<Controller>>? dynamically


I am trying to create a lambda expression of type Expression.Lambda<Action<Controller>> dynamically.

For instance: x => x.Index()

var body = ???
Expression<Action<Controller>> action = Expression.Lambda<Action<Controller>>(body);

I have the controller type (Type) and the controller action (MemberInfo).


Solution

  • If I understand your question correctly, you would do it using Expression.Call(). Something like:

    Expression<Action<T>> CreateCallExpression<T>(MethodInfo method)
    {
        var parameter = Expression.Parameter(typeof(T), "x");
        return Expression.Lambda<Action<T>>(
            Expression.Call(parameter, method), parameter);
    }