I have an expression like this:
Expression<Func<int, bool>> exp = i => i<15 && i>10;
I want to add a condition to exp
after this line. How can I do this?
Simply with this:
Expression<Func<int, bool>> exp = i => i < 15 && i > 10;
var compiled = exp.Compile();
exp = i => compiled(i) && i % 2 == 0; //example additional condition
Note that you can't do it like this:
exp = i => exp.Compile()(i) && i % 2 == 0; //example additional condition
because exp
will be added to the closure by reference and as a result, calling it will cause a StackOverflowException
.
You have two options. The first one is the version of BartoszKP, to blackbox the first expression and use it afterwards. However, while this has a great syntax support, it also means that systems like the Entity Framework cannot really use the expression, because it is blackboxed. If this expression was used in a database query, the EF could not check this predicate on the server, but has to retrieve all the data to the client, if it works at all.
Thus, if you want to use the expression e.g. for a database query, you have to use the Expression API, i.e.
Expression<Func<int, bool>> exp = i => i<15 && i>10;
exp = Expression.Lambda<Func<int, bool>>(Expression.AndAlso(exp.Body, ...), exp.Parameters[0]);
The three dots indicate the expression that you want to insert as second part. You could use another expression created by the compiler, but you would then have to replace the parameters.
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