How do I dynamically create an Expression> p

2019-01-08 10:34发布

问题:

How would I go about using an Expression Tree to dynamically create a predicate that looks something like...

(p.Length== 5) && (p.SomeOtherProperty == "hello") 

So that I can stick the predicate into a lambda expression like so...

q.Where(myDynamicExpression)...

I just need to be pointed in the right direction.

Update: Sorry folks, I left out the fact that I want the predicate to have multiple conditions as above. Sorry for the confusion.

回答1:

Original

Like so:

    var param = Expression.Parameter(typeof(string), "p");
    var len = Expression.PropertyOrField(param, "Length");
    var body = Expression.Equal(
        len, Expression.Constant(5));

    var lambda = Expression.Lambda<Func<string, bool>>(
        body, param);

Updated

re (p.Length== 5) && (p.SomeOtherProperty == "hello"):

var param = Expression.Parameter(typeof(SomeType), "p");
var body = Expression.AndAlso(
       Expression.Equal(
            Expression.PropertyOrField(param, "Length"),
            Expression.Constant(5)
       ),
       Expression.Equal(
            Expression.PropertyOrField(param, "SomeOtherProperty"),
            Expression.Constant("hello")
       ));
var lambda = Expression.Lambda<Func<SomeType, bool>>(body, param);


回答2:

Use the predicate builder.

http://www.albahari.com/nutshell/predicatebuilder.aspx

Its pretty easy!



回答3:

To combine several predicates with the && operator, you join them together two at a time.

So if you have a list of Expression objects called predicates, do this:

Expression combined = predicates.Aggregate((l, r) => Expression.AndAlso(l, r));


回答4:

To associate Lambda expression each other: An other way is to use the following code. It s more flexible than the Schotime answer in my advice and work perfectly. No external Nuggets needed

Framework 4.0

    // Usage first.Compose(second, Expression.And)
    public static Expression<T> Compose<T>(this Expression<T> First, Expression<T> Second, Func<Expression, Expression, Expression> Merge)
    {
        // build parameter map (from parameters of second to parameters of first)
        Dictionary<ParameterExpression,ParameterExpression> map = First.Parameters.Select((f, i) => new { f, s = Second.Parameters[i] }).ToDictionary(p => p.s, p => p.f);

        // replace parameters in the second lambda expression with parameters from the first
        Expression secondBody = ParameterRebinder.ReplaceParameters(map, Second.Body);

        // apply composition of lambda expression bodies to parameters from the first expression 
        return Expression.Lambda<T>(Merge(First.Body, secondBody), First.Parameters);
    }

    public static Expression<Func<T, bool>> And<T>(this Expression<Func<T, bool>> First, Expression<Func<T, bool>> Second)
    {
        return First.Compose(Second, Expression.And);
    }

    public static Expression<Func<T, bool>> Or<T>(this Expression<Func<T, bool>> First, Expression<Func<T, bool>> second)
    {
        return First.Compose(second, Expression.Or);
    }


public class ParameterRebinder : ExpressionVisitor
{
    private readonly Dictionary<ParameterExpression, ParameterExpression> map;

    public ParameterRebinder(Dictionary<ParameterExpression, ParameterExpression> map)
    {
        this.map = map ?? new Dictionary<ParameterExpression, ParameterExpression>();
    }

    public static Expression ReplaceParameters(Dictionary<ParameterExpression, ParameterExpression> map, Expression exp)
    {
        return new ParameterRebinder(map).Visit(exp);
    }

    protected override Expression VisitParameter(ParameterExpression p)
    {
        ParameterExpression replacement;
        if (map.TryGetValue(p, out replacement))
        {
            p = replacement;
        }
        return base.VisitParameter(p);
    }
}