Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extend a lambda expression

Tags:

c#

lambda

I have a existing lambda-expression which was created like:

Expression<Func<Entities.Area, bool>> where = (x => (x.Created > this.Value || (x.Changed != null && x.Changed > this.Value)));

Now, I have to extend this expression with this one:

Expression<Func<Entities.Area, bool>> whereAdd = (x => x.Client.Id == ClientInfo.CurrentClient.Id);

The Result should be like:

Expression<Func<Entities.Area, bool>> where = (x => (x.Created > this.Value || (x.Changed != null && x.Changed > this.Value)) && x.Client.Id == ClientInfo.CurrentClient.Id);

I cannot change the creation of the first expression directly because it is not my code.

I hope someone can help me how to extend the first lambda-expression.

like image 378
BennoDual Avatar asked Nov 01 '22 02:11

BennoDual


1 Answers

Just create a new AndAlso expression taking the bodies of both your expressions and make a new lambda expression out of that:

ParameterExpression param = Expression.Parameter(typeof(Entities.Area), "x");
Expression body = Expression.AndAlso(where.Body, whereAdd.Body);

var newWhere = Expression.Lambda<Func<Entities.Area, bool>>(body, param);

Console.WriteLine(newWhere.ToString());
// x => (((x.Created > Convert(value(UserQuery).Value)) OrElse ((x.Changed != null) AndAlso (x.Changed > Convert(value(UserQuery).Value)))) AndAlso (x.Client.Id == ClientInfo.CurrentClient.Id))
like image 140
poke Avatar answered Nov 09 '22 08:11

poke