5

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.

BennoDual
  • 5,865
  • 15
  • 67
  • 153

2 Answers2

2

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))
poke
  • 369,085
  • 72
  • 557
  • 602
0

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]);
Community
  • 1
  • 1
Jude
  • 2,353
  • 10
  • 46
  • 70
  • 2
    Could you please [edit] your answer to give an explanation of why this code answers the question? Code-only answers are [discouraged](http://meta.stackexchange.com/questions/148272), because they don't teach the solution. – DavidPostill Jun 07 '15 at 16:18
  • I gave a link first as a comment upthere. After half an hour poke's answer was still not accepted. So I modified Marc Gravel's answer (which I already linked) and posted it. What explanation can I do for that? Honestly, surprising thing is queston was upvoted three times. Many answers around for 'AndAlso' at SO. Quick search would be enough for solution. – Jude Jun 07 '15 at 16:29
  • Fair enough, but I would stick the link from your comment into the anser as a for further explanation see [Combining two expressions (Expression>)](http://stackoverflow.com/a/457328) – DavidPostill Jun 07 '15 at 16:42