Skip to content

Instantly share code, notes, and snippets.

@janvanderhaegen
Created September 5, 2014 19:59
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save janvanderhaegen/1620fee98ea8578862aa to your computer and use it in GitHub Desktop.
Save janvanderhaegen/1620fee98ea8578862aa to your computer and use it in GitHub Desktop.
C# code to combine two lambda expressions
//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);
}
}
}
@BabaDorin
Copy link

💖

Copy link

ghost commented Feb 22, 2022

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