Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I'm assuming that the function is actually named <code>FindChildrenById</code>, otherwise I can't see any recursion going on.</p> <p>Under this assumption you can either use exceptions (which I would strongly recommend against), or return a <code>KeyValuePair&lt;bool, IEnumerable&lt;Node&gt;&gt;</code> where the <code>bool</code> part will be used to signal an early out up the chain.</p> <p>Then, on the API level, expose a wrapper method that simply returns the <code>IEnumerable&lt;Node&gt;</code> part and throws way the <code>bool</code> part.</p> <p>Here's an example, given the class <code>Node</code>:</p> <pre><code>public class Node { List&lt;Node&gt; children; public string Text { get; set; } public List&lt;Node&gt; Children { get { return children ?? (children = new List&lt;Node&gt;()); } } } </code></pre> <p>You can traverse and shortcut like this:</p> <pre><code>public class NodeTraverser { private static KeyValuePair&lt;bool, IEnumerable&lt;Node&gt;&gt; GetChildrenById(string text, Node node) { if(node.Text == text) { return new KeyValuePair&lt;bool,IEnumerable&lt;Node&gt;&gt;(true, node.Children); } foreach(var child in node.Children) { var result = GetChildrenById(text, child); if(result.Key) { return result; // early out } } return new KeyValuePair&lt;bool,IEnumerable&lt;Node&gt;&gt;(false, Enumerable.Empty&lt;Node&gt;()); } public static IEnumerable&lt;Node&gt; FindChildrenbyId(string text, Node root) { return GetChildrenById(text, root).Value; } } </code></pre>
 

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