Stop traversal with ExpressionVisitor
Asked Answered
D

1

7

I am using the ExpressionVisitor to parse an expression tree to find out if it contains a specified parameter. Once I have found the parameter, there is no point in continuing the traversal.

Is there any way to stop the traversal with the visitor pattern in general and more specifically with the ExpressionVisitor in .NET?

This is what I have so far, and it is working as expected. But once the boolean flag is set to true it would make sense to stop the traversal as far as this algorithm goes.

public class ExpressionContainsParameterVisitor : ExpressionVisitor
{
  private bool expressionContainsParameter_;
  private ParameterExpression parameter_;

  public bool Parse(Expression expression, ParameterExpression parameterExpression)
  {
    parameter_ = parameterExpression;
    expressionContainsParameter_ = false;

    Visit(expression);

    return expressionContainsParameter_;
  }

  protected override Expression VisitParameter(ParameterExpression node)
  {
    if (node == parameter_)
    {
      expressionContainsParameter_ = true;
    }

    return node;
  }
}
Durable answered 20/4, 2016 at 8:2 Comment(0)
M
10

I think that the best you could do would be to override the Visit method so that it stops dispatching once the flag is set.

Something along the lines of:

public override Expression Visit(Expression node)
{
  if(expressionContainsParameter_) return node;
  return base.Visit(node);
}

This should allow the traversal to "unwind" as quickly as possible, even if you're currently nested several Visit calls deep at the time.

Maddux answered 20/4, 2016 at 8:25 Comment(1)
Thanks, that makes sense.Durable

© 2022 - 2024 — McMap. All rights reserved.