c #: Navigate between the automation elements of the Microsoft user interface using TreeWalker

I wrote a method that finds a secondary element in a menu based on some condition. The code works, but in cases where I look for more elements that are very low in the structure of the tree, it will take a long time to do it.

Usually, when I write some tests that use this method, the elements I'm looking for are very close, so I think it does not make sense to start the search again from the top. I want to start again in some way from the position of the last found element and do a search in the vicinity (that is, look first at the main node of the found element and the other secondary ones in the main node) of that position and if that fails, execute the method that I wrote that starts from the root.

The code looks like this:

Static AutomationElement protected FindAutomationElement (TmUIElementBase parent, Condition condition) {
var walker = TreeWalker.ControlViewWalker;
var worklist = new Queue();
worklist.Enqueue (parent.SearchFrom);
while (worklist.Any ()) {
var element = worklist.Dequeue ();
var child = walker.GetFirstChild (item);
while (child! = null) {
var result = child.FindFirst (TreeScope.Element, condition);
yes (result! = null) {
return result
}
worklist.Enqueue (child);
child = walker.GetNextSibling (child);
}
}
throw a new exception ("FindAutomationElement: Element not found");
}