How do I dynamically create an Expression<Func<MyClass, bool>> predicate?
Asked Answered
A

5

30

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.

Asiatic answered 10/5, 2009 at 10:22 Comment(0)
Q
55

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);
Quietly answered 10/5, 2009 at 10:33 Comment(4)
Thanks, but stupidly I forgot to mention that I'd like the predicate to read like... (p.Length == 5) && (p.SomeOtherProperty == "hello"). In other words, how do I chain the conditions? Sorry for not having been clearAsiatic
Thanks alot for the update. Seems to be what I was looking for. ThanksAsiatic
@Mark Gravell: if we didn't have SomeType how we can create lambda. e.g: we have just Type TyepOfEntity = Assembly.GetType(string.Format("Smartiz.Data.{0}", EntityName));Wartburg
@Mohammad then you use "object" and include type conversion steps in the Expression. Not at a computer, but it'll be Expression.Cast or Expression.Convert or Expression.ChangeType or similarQuietly
C
14

Use the predicate builder.

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

Its pretty easy!

Chickpea answered 24/5, 2010 at 0:32 Comment(0)
P
9

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));
Perfectible answered 10/5, 2009 at 11:50 Comment(0)
R
1

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);
    }
}
Role answered 3/9, 2015 at 12:41 Comment(0)
M
0

I have a open-source project called Exprelsior that provides very simple ways to create dynamic predicates:

Based on your example:

var exp1 = ExpressionBuilder.CreateBinary<YourClass>("MyProperty.Length", 5, ExpressionOperator.Equals);

var exp2 = ExpressionBuilder.CreateBinary<YourClass>("SomeOtherProperty", "hello", ExpressionOperator.Equals);

var fullExp = exp1.And(exp2);

// Use it normally...
q.Where(fullExp)

It even supports full text predicate generation, so you can receive any dynamic query from an HTTP GET method, for example:

var exp1 = ExpressionBuilder.CreateBinaryFromQuery<YourClass>("eq('MyProperty.Length', '5')");

var exp2 = ExpressionBuilder.CreateBinaryFromQuery<YourClass>("eq('SomeOtherProperty', 'hello')");

var fullExp = exp1.And(exp2);

// Use it normally...
q.Where(fullExp)

It supports a lot more data types and operators.

Link: https://github.com/alexmurari/Exprelsior

Matlock answered 5/11, 2019 at 16:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.