扩展lambda表达式

时间:2015-06-07 14:18:35

标签: c# lambda

我有一个现有的lambda表达式,其创建方式如下:

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

现在,我必须用这个表达式扩展这个表达式:

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

结果应该是:

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

我无法直接更改第一个表达式的创建,因为它不是我的代码。

我希望有人可以帮助我扩展第一个lambda表达式。

2 个答案:

答案 0 :(得分:2)

只需创建一个新的AndAlso表达式,取两个表达式的主体,并从中创建一个新的lambda表达式:

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

答案 1 :(得分:-1)

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