BennoDual
BennoDual

Reputation: 6259

Extend a lambda expression

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.

Upvotes: 5

Views: 3327

Answers (2)

Jude
Jude

Reputation: 2433

Combining two expressions (Expression<Func<T, bool>>)

var body = Expression.AndAlso(where.Body, whereadd.Body);
var lambda = Expression.Lambda<Func<Entities.Area,bool>>(body, where.Parameters[0]);

Upvotes: 0

poke
poke

Reputation: 387557

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))

Upvotes: 2

Related Questions