1

I need to find all calls to particular method in expression tree which can be very complex. Currently I have simple recursive code which checks for BinaryExpression, ConditionalExpression etc and of course for MethodCallExpression. It works but I wonder if there is simpler way?

What I need is an iterator for all MethodCallExpression in complex expression so I can just check MethodCallExpression and don't care about other types of expression in my tree. Is something like this builtin for example somewhere in System.Linq.Expressions?

Pol
  • 5,064
  • 4
  • 32
  • 51

1 Answers1

3

As svick correctly points out: use the ExpressionVisitor base class:

http://msdn.microsoft.com/en-us/library/system.linq.expressions.expressionvisitor.aspx

If you want to roll your own or see how ExpressionVisitor works, in this article Matt Warren shows you how to rebuild an expression tree by visiting every node.

http://blogs.msdn.com/b/mattwar/archive/2007/07/31/linq-building-an-iqueryable-provider-part-ii.aspx

You don't need to rebuild it, you just need to search it. You can modify Matt's code so that it does not return a new rebuilt expression, it just recursively searches each child node.

Eric Lippert
  • 647,829
  • 179
  • 1,238
  • 2,067
  • 3
    Or just use the base class that's already included in the Framework: [`ExpressionVisitor`](http://msdn.microsoft.com/en-us/library/system.linq.expressions.expressionvisitor.aspx). – svick Apr 16 '13 at 00:38
  • @svick: Good point, I had forgotten that we started including that. – Eric Lippert Apr 16 '13 at 00:59