Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>There are two common ways to process a recursive structure in C# - by using <code>yield return</code> and by writing a recursive function. I prefer the second way, here is an example:</p> <pre><code>public static class TreeUtils { public static IEnumerable&lt;T&gt; GetAllNodes&lt;T&gt;( this T node , Func&lt;T,IEnumerable&lt;T&gt;&gt; f) { return GetAllNodes(new[] {node}, f); } public static IEnumerable&lt;T&gt; GetAllNodes&lt;T&gt;( this IEnumerable&lt;T&gt; e , Func&lt;T,IEnumerable&lt;T&gt;&gt; f) { return e.SelectMany(c =&gt; f(c).GetAllNodes(f)).Concat(e); } } </code></pre> <p>You can use this utility class as follows:</p> <pre><code>class TreeNode&lt;T&gt; { public T Content {get; set;} public IEnumerable&lt;TreeNode&lt;T&gt;&gt; Dependents {get;set;} } foreach (TreeNode node in TreeUtils.GetAllNodes(root, n =&gt; n.Dependents)) { Console.WriteLine(node.Content); } </code></pre> <p>A somewhat cheating way would be to employ a "recursive" lambda:</p> <pre><code>using System; using System.Collections.Generic; public class Program { class Node { public int Data; public IEnumerable&lt;Node&gt; Dependents { get; set; } } public static void Main() { var root = Create( 10 , Create(5, Create(3), Create(7, Create(6), Create(8))) , Create(20, Create(15), Create(30, Create(28), Create(40))) ); // We cannot combine the declaration and definition here Func&lt;Node,IEnumerable&lt;Node&gt;&gt; all = null; // The recursive magic is in the following line all = n =&gt; n.Dependents.SelectMany(d =&gt; all(d)).Concat(new[] {n}); // Here is how you can use it foreach (var node in all(root)) { Console.WriteLine(node.Data); } } // Helper function for creating tree nodes private static Node Create(int data, params Node[] nodes) { return new Node { Data = data, Dependents = nodes }; } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

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