Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 245
Senkwe Avatar asked May 10 '09 10:05

Senkwe


People also ask

What is tree expressions C#?

Expression trees represent code in a tree-like data structure, where each node is an expression, for example, a method call or a binary operation such as x < y . You can compile and run code represented by expression trees.


2 Answers

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); 
like image 106
Marc Gravell Avatar answered Oct 18 '22 16:10

Marc Gravell


Use the predicate builder.

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

Its pretty easy!

like image 34
Schotime Avatar answered Oct 18 '22 17:10

Schotime