I have the following method that works well, except the yield break statement only breaks out of the current enumerator. I understand why this is the case, but I am drawing a blank over how to propogate the yield break up through the recursive stack.
private static IEnumerable<Node> FindChildrenById(IEnumerable nodes, string parentText) {
var en = nodes.GetEnumerator();
var targetFound = false;
while (en.MoveNext()) {
var node = en.Current as Node;
if (node != null)
{
if (node.Parent == null && string.IsNullOrEmpty(parentText))
{
//Returns the top level nodes if an empty parentIdis entered
targetFound = true;
yield return node;
}
else if (node.Parent != null && node.Parent.Text == parentText)
{
//returns the nodes belonging to the parent
yield return node;
}
else
{
//Recurse into the children to see whether one of these is the node to find
foreach (var nd in FindChildrenById(node.Nodes, parentText))
{
yield return nd;
}
}
}
}
if (targetFound)
{
yield break;
}
}
So when I have the following nodes and pass "Top 2 a" as the parentText...
Top 1
Top 1 a
Top 1 b
Top 2
Top 2 a
Top 2 aa
Top 2 ab
Top 2 ac
Top 2 b
Top 3
Top 3 a
Top 3 b
Top 4
... then I get the result:
Top 2 aa
Top 2 ab
Top 2 ac
This is the correct result, however, when I step through my code, the outer-most loop continues to process Top 3 and Top 4. How do I break out of this outer loop?