Convert Expression to Expression.Lambda>

c# expression-trees lambda

Question

I have a method that builds an expression tree, based on the Type of the object that is passed to the method. Once the tree is built, I want to convert it and return it with the return type as is shown below.

public static Expression<Func<object, bool>> BuildExpression(Type type, ...)
{
    // build the expression...
    ParameterExpression param = Expression.Parameter(type, "m");
    Expression expression = null;

    // simplified version of building the expression tree
    MemberExpression member = Expression.Property(param, filter.Property);
    ConstantExpression constant = Expression.Constant(filter.Value);
    expression = Expression.Equal(member, constant);

   // ...

   // IT FAILS ON THIS LINE!!!
   return Expression.Lambda<Func<object, bool>>(expression, param);
}

I've looked at a few conversion answers, but to no avail. Any advice?

1
1
2/4/2016 4:24:01 PM

Popular Answer

Here is your code with modifications as described in my previous comment.

1) Your function returns expression that describes function with single argument. And this argument is of type Object. So you should use Object type when creating parameter "m" expression.

2) Before accessing the property parameter should be cast back to desired type. See Expression.Convert.

public static Expression<Func<object, bool>> BuildExpression(Type type, ...)
{
    // build the expression...
    ParameterExpression param = Expression.Parameter(typeof(Object), "m");
    Expression expression = null;

    UnaryExpression convert = Expression.Convert(param, type);

    // simplified version of building the expression tree
    MemberExpression member = Expression.Property(convert, filter.Property);
    ConstantExpression constant = Expression.Constant(filter.Value);
    expression = Expression.Equal(member, constant);

    // ...

    return Expression.Lambda<Func<object, bool>>(expression, param);
}
0
2/4/2016 8:47:58 PM


Related Questions





Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow