Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add another condition to an expression?

Tags:

c#

linq

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?

like image 424
Mostafa Soghandi Avatar asked Feb 26 '14 11:02

Mostafa Soghandi


Video Answer


2 Answers

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.

like image 187
BartoszKP Avatar answered Oct 23 '22 11:10

BartoszKP


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.

like image 35
Georg Avatar answered Oct 23 '22 11:10

Georg