Pol
Pol

Reputation: 5134

Finding method call in expression tree / iterating expression tree

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?

Upvotes: 1

Views: 837

Answers (1)

Eric Lippert
Eric Lippert

Reputation: 660463

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.

Upvotes: 3

Related Questions