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.

abatishchev
  • 98,240
  • 88
  • 296
  • 433
Senkwe
  • 2,256
  • 3
  • 24
  • 33

5 Answers5

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);
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • 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 clear – Senkwe May 10 '09 at 11:00
  • Thanks alot for the update. Seems to be what I was looking for. Thanks – Senkwe May 10 '09 at 17:10
  • @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));` – Mohammad Dayyan Dec 13 '13 at 12:21
  • 1
    @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 similar – Marc Gravell Dec 13 '13 at 17:39
14

Use the predicate builder.

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

Its pretty easy!

Schotime
  • 15,707
  • 10
  • 46
  • 75
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));
Daniel Earwicker
  • 114,894
  • 38
  • 205
  • 284
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);
    }
}
Alan
  • 9
  • 3
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

MurariAlex
  • 321
  • 1
  • 3
  • 20