3

I don't do expression tree work enough to get this working...

Essentially what I want to create is m.MyProperty == 1, to be used in a method that takes Func<T, bool>.

I have a MemberExpression already. I've tried various things, but I just keep getting different errors.

I currently have something like this (that doesn't work):

object const = 1;
var equalExpression = Expression.Equal( memberExpression, Expression.Constant( const ) );
var compiled = Expression.Lambda<Func<T, bool>>( equalExpression, Expression.Parameter( typeof( T ) ).Compile();

This gives me an exception:

System.InvalidOperationException: variable 'm' of type 'MyType' referenced from scope '', but it is not defined

I've tried re-working several different parts of this but haven't come up with anything that works.

The const is an object that can be any type, but should match the type of the MemberExpression.

Solution:

object c = 1;
var parameterExpression = (ParameterExpression)memberExpression.Expression;
var equalExpression = Expression.Equal(memberExpression, Expression.Constant(c));
var compiled = Expression.Lambda<Func<T, bool>>(equalExpression, parameterExpression).Compile();
4

1 に答える 1