Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Joining lambda Expressions

Tags:

c#

lambda

How would I go about joining two lambda expressions like theese:

Expression<Func<string, bool>> expr1 = a => a.Length > 100;
Expression<Func<string, bool>> expr2 = b => b.Length < 200;

... into an expression like this:

Expression<Func<string, bool>> expr3 = s => s.Length < 100 && s.Length < 200;

That is, joining them with an AndAlso operator. (Or any other operator for that matter...)

I actually succeeded with some nasty recursive replacement of lambda parameters and then joining with the Expression.AndAlso method. But I'm looking for something more simple.

For example something like: (Which obviously doesn't work.)

Expression<Func<string, bool>> expr3 = c => expr1(a) && expr2(b);
like image 272
LaZe Avatar asked Mar 01 '10 18:03

LaZe


1 Answers

Your "something like" would work if you were dealing with normal delegates. But if you have to use expression trees, I don't see any other solution than recursive replacement.

In .NET 4, you can use the System.Linq.Expressions.ExpressionVisitor to make this kind of recursive replacement much easier. For .NET 3.5, take a look at this sample: http://msdn.microsoft.com/en-us/library/bb882521.aspx

Using the ExpressionVisitor, you only have to override methods for the node types you want to replace and the surrounding tree will be automatically reconstructed.

If you are dealing with conditions for use with LINQ, a much easier solution to dynamically combine conditions is to just call Where() multiple times.

like image 56
Daniel Avatar answered Sep 27 '22 19:09

Daniel