Skip to content

Instantly share code, notes, and snippets.

@janvanderhaegen
Created September 5, 2014 19:59
Show Gist options
  • Select an option

  • Save janvanderhaegen/1620fee98ea8578862aa to your computer and use it in GitHub Desktop.

Select an option

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 Markdown

πŸ’–

ghost commented Feb 22, 2022

Copy link
Copy Markdown

I had to use "AndAlso" instead of "And" on order to get it to work in "all" conditions.

@lutecki

lutecki commented May 31, 2026

Copy link
Copy Markdown

πŸ‘

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment