Reputation: 5134
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
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