Note that there are some explanatory texts on larger screens.

plurals
  1. POHow do I break out of recursive IEnumerable<T> loops using yield break?
    text
    copied!<p>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.</p> <pre><code> private static IEnumerable&lt;Node&gt; 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 &amp;&amp; string.IsNullOrEmpty(parentText)) { //Returns the top level nodes if an empty parentIdis entered targetFound = true; yield return node; } else if (node.Parent != null &amp;&amp; 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; } } </code></pre> <p>So when I have the following nodes and pass "Top 2 a" as the parentText...</p> <pre><code>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 </code></pre> <p>... then I get the result:</p> <pre><code>Top 2 aa Top 2 ab Top 2 ac </code></pre> <p>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?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload