Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you create a lambda expression from a MemberExpression

Tags:

c#

lambda

My ultimate goal is to iterate through nested properties in a lambda expression and determine if any of the properties are null, but I am having trouble creating a new lambda expression based on a member expression.

Take this dummy method:

public static void DoStuff<TModelDetail, TValue>(Expression<Func<TModelDetail, TValue>> expr, TModelDetail detail)
{
    var memberExpression = expr.Body as MemberExpression;
    if (memberExpression == null && expr.Body is UnaryExpression)
    {
        memberExpression = ((UnaryExpression)expr.Body).Operand as MemberExpression;
    }

    var pe = Expression.Parameter(typeof(TModelDetail), "x");
    var convert = Expression.Convert(memberExpression, typeof(object));
    var wee = Expression.Lambda<Func<TModelDetail, object>>(convert, pe);
    var hey = wee.Compile()(detail);            
}

On the Compile.exec line I get the following error:

variable 'x' of type 'Blah' referenced from scope '', but it is not defined

where Blah is the type of TModelDetail.

How do I build the lambda with the MemberExpression? What I ultimately want to do is recursively find the root member expression, determine if it is null, and bubble up and determine if each subsequent member expression is null.

like image 819
dtryan Avatar asked Dec 15 '17 06:12

dtryan


1 Answers

expr already contains a parameter (let's call it y) which is bound by your member expression, so expr looks like y => y.Member.Something.

When your construct the new lambda Expression wee you are giving it a new parameter x, so wee looks like x => y.Member, which doesn’t make sense.

Therefore you need to reuse the parameter from expr for wee.

like image 89
ckuri Avatar answered Oct 15 '22 02:10

ckuri