Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>This code should do the trick</p> <pre><code>public static class Extensions { public static IEnumerable&lt;T&gt; GetRecursively&lt;T&gt;(this IEnumerable collection, Func&lt;T, IEnumerable&gt; selector) { foreach (var item in collection.OfType&lt;T&gt;()) { yield return item; IEnumerable&lt;T&gt; children = selector(item).GetRecursively(selector); foreach (var child in children) { yield return child; } } } } </code></pre> <p>Here's an example of how to use it</p> <pre><code>TreeView view = new TreeView(); // ... IEnumerable&lt;TreeNode&gt; nodes = view.Nodes. .GetRecursively&lt;TreeNode&gt;(item =&gt; item.Nodes); </code></pre> <p><strong>Update:</strong> In response to Eric Lippert's post.</p> <p>Here's a much improved version using the technique discussed in <a href="http://blogs.msdn.com/wesdyer/archive/2007/03/23/all-about-iterators.aspx" rel="nofollow noreferrer">All About Iterators</a>.</p> <pre><code>public static class Extensions { public static IEnumerable&lt;T&gt; GetItems&lt;T&gt;(this IEnumerable collection, Func&lt;T, IEnumerable&gt; selector) { Stack&lt;IEnumerable&lt;T&gt;&gt; stack = new Stack&lt;IEnumerable&lt;T&gt;&gt;(); stack.Push(collection.OfType&lt;T&gt;()); while (stack.Count &gt; 0) { IEnumerable&lt;T&gt; items = stack.Pop(); foreach (var item in items) { yield return item; IEnumerable&lt;T&gt; children = selector(item).OfType&lt;T&gt;(); stack.Push(children); } } } } </code></pre> <p>I did a simple performance test using the following <a href="https://stackoverflow.com/questions/1507405/c-is-this-benchmarking-class-accurate">benchmarking technique</a>. The results speak for themselves. The depth of the tree has only marginal impact on the performance of the second solution; whereas the performance decreases rapidly for the first solution, eventually leadning to a <code>StackOverflowException</code> when the depth of the tree becomes too great.</p> <p><img src="https://i.stack.imgur.com/iI4JO.png" alt="benchmarking"></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