Created
September 5, 2014 19:59
-
-
Save janvanderhaegen/1620fee98ea8578862aa to your computer and use it in GitHub Desktop.
C# code to combine two lambda expressions
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Shoutout to MBoros on stackoverflow | |
public static class ExpressionCombiner { | |
public static Expression<Func<T, bool>> And<T>(this Expression<Func<T, bool>> exp, Expression<Func<T, bool>> newExp) | |
{ | |
// get the visitor | |
var visitor = new ParameterUpdateVisitor(newExp.Parameters.First(), exp.Parameters.First()); | |
// replace the parameter in the expression just created | |
newExp = visitor.Visit(newExp) as Expression<Func<T, bool>>; | |
// now you can and together the two expressions | |
var binExp = Expression.And(exp.Body, newExp.Body); | |
// and return a new lambda, that will do what you want. NOTE that the binExp has reference only to te newExp.Parameters[0] (there is only 1) parameter, and no other | |
return Expression.Lambda<Func<T, bool>>(binExp, newExp.Parameters); | |
} | |
class ParameterUpdateVisitor : ExpressionVisitor | |
{ | |
private ParameterExpression _oldParameter; | |
private ParameterExpression _newParameter; | |
public ParameterUpdateVisitor(ParameterExpression oldParameter, ParameterExpression newParameter) | |
{ | |
_oldParameter = oldParameter; | |
_newParameter = newParameter; | |
} | |
protected override Expression VisitParameter(ParameterExpression node) | |
{ | |
if (object.ReferenceEquals(node, _oldParameter)) | |
return _newParameter; | |
return base.VisitParameter(node); | |
} | |
} | |
} |
I had to use "AndAlso" instead of "And" on order to get it to work in "all" conditions.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
💖