Note: I know it's much simple to create this using dynamic linq but I want to learn.
I want to create a lambda that "finds": Name=David AND Age=10.
class Person { public int Age { get; set; } public string Name { get; set; } } var lambda = LabmdaExpression<Person>("Name", "David", "Age", 10); static Expression<Func<T, bool>> LabmdaExpression<T>(string property1, string value1, string property2, int value2) { ParameterExpression parameterExpression = Expression.Parameter(typeof(Person), "o"); MemberExpression memberExpression1 = Expression.PropertyOrField(parameterExpression, property1); MemberExpression memberExpression2 = Expression.PropertyOrField(parameterExpression, property2); ConstantExpression valueExpression1 = Expression.Constant(value1, typeof(string)); ConstantExpression valueExpression2 = Expression.Constant(value2, typeof(int)); BinaryExpression binaryExpression1 = Expression.Equal(memberExpression1, valueExpression1); BinaryExpression binaryExpression2 = Expression.Equal(memberExpression2, valueExpression2); var ret1 = Expression.Lambda<Func<T, bool>>(binaryExpression1, parameterExpression); var ret2 = Expression.Lambda<Func<T, bool>>(binaryExpression2, parameterExpression); }
That's the basics of building an expression tree in memory. More complex trees generally mean more node types, and more nodes in the tree. Let's run through one more example and show two more node types that you will typically build when you create expression trees: the argument nodes, and method call nodes.
In 2010, the Dynamic Type was introduced and that gave us the ability to create dynamic lambda expressions.
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.
Expression Trees provide richer interaction with the arguments that are functions. You write function arguments, typically using Lambda Expressions, when you create LINQ queries. In a typical LINQ query, those function arguments are transformed into a delegate the compiler creates.
Expression andExpression = Expression.AndAlso(binaryExpression1, binaryExpression2); return Expression.Lambda<Func<T, bool>>(andExpression , parameterExpression);
Edit - comment
You just chain together all your expresions
so in order to get this expression X AND (Y OR (Z OR Q))
Expression ZorQ = Expression.OrElse(zExp, qExp); Expression YorZorQ = Expression.OrElse(yExp, ZorQ); Expression XandYorZorQ = Expression.AndAlso(xExp, YorZorQ);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With