Friday, May 6, 2011

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

Hi all,

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.

Thanks.

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

From stackoverflow
  • 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);
    
    Hovito : 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
    Hovito : Thanks alot for the update. Seems to be what I was looking for. Thanks
  • You could instantiate the expression and look at it with an Expression Tree visualizer. There is one in the Visual studio samples - you can compile it and then put it in a specific folder.

    That will give you a nice little tree that shows you how an expression is made up. Then you could construct such an expression with the static methods of the Expression object.

  • 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));
    
    Marc Gravell : Actually, you mean Expression.AndAlso. Expression.And is the bitwise and - i.e. where 2 & 1 = 3
    Daniel Earwicker : Thanks, corrected it.
  • Use the predicate builder.

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

    Its pretty easy!

0 comments:

Post a Comment