Search code examples
c#lambdaexpression-trees

C# refactoring lambda expressions


I have several Expression<Func<User,bool>> expressions that shares properties. For example,

Expression<Func<User, bool>> e1 = 
  (User u) => u.IsActive && u.Group != "PROCESS" && u.Name != null;
Expression<Func<User, bool>> e2 = 
  (User u) => u.IsActive && u.Group != "PROCESS" && u.Name != "A";
Expression<Func<User, bool>> e3 = 
  (User u) => u.IsActive && u.Group != "PROCESS" && u.Name != "B";

Is there an easy way to put the u.IsActive && u.Group != "PROCESS" in a variable and use it in e1, e2 and e3? Edited : And I still want the same tree.

Seems I can do it by building the expression with Expression.Lambda<Func<User, bool>>(BinaryExpression.AndAlso( etc... But rather than simplifying my code it made it more difficult to read.


Solution

  • I believe there's no cleaner way to do that for your case. You can use BinaryExpression as you mentioned. You can encapsulate the BinaryExpression and Expression.Lambda calls into a method and call that instead (like PredicateBuilder.And) but none of those are as clean as the current syntax IMO.