The problem with lambda expressions is that they are immutable, and you cannot easily replace lambda parameters. My original idea was to do something like this ( unfortunately, this will not work ):
public static class ExpressionExtesions { public static Expression<Func<T, bool>> And<T>(this Expression<Func<T, bool>> baseCondition, Expression<Func<T, bool>> additionalCondition) { var and = Expression.AndAlso(baseCondition.Body, additionalCondition.Body); return Expression.Lambda<Func<T, bool>>(and, baseCondition.Parameters);
and use in code:
Expression<Func<User, bool>> e = usr => usr.IsActive && usr.Group != "PROCESS"; var e1 = e.And(u => u.Name != null); var e2 = e.And(u => u.Name != "A"); var e3 = e.And(u => u.Name != "B");
Possible Solution
You can try to use one of the projects aimed at implementing expression builders. I have not used any of them, but google provides many links, for example:
Another approach
If you use these expressions in LINQ to filter values, you can use a different approach (do not combine expressions, but combine filters):
var activeUsers = allUsers.Where(usr => usr.IsActive && usr.Group != "PROCESS"); var usersAll = activeUsers.Where(u => u.Name != null); var usersNotA = activeUsers.Where(u => u.Name != "A"); var usersNotB = activeUsers.Where(u => u.Name != "B");
Konstantin spirin
source share