Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<h2>Here is all about recursion and a proper data structure.</h2> <p>So here is all about recursion. You already started implementing that way, so this is good.</p> <p>First things first. Data structure. To represent the tree like menu you should build tree like liked object, so you have to create simple graph of them. You started well. You have a <code>Box</code> object. Lets now enhance it. Create a <code>BoxNode</code> object that have a List of Boxes, like so:</p> <pre><code>public class BoxNode { public List&lt;Box&gt; BoxChildren { get; set; } } </code></pre> <p>Then <code>Box</code>:</p> <pre><code>public class Box { public string Name { get; set; } public BoxNode BoxNode { get; set; } } </code></pre> <p>So now we have the basic data structure, lets go to the function:</p> <pre><code> public static void CreateMenuTree(BoxNode boxNode, string indent) { foreach (Box box in boxNode.BoxChildren) { Console.WriteLine(indent + box.Name); if (box.BoxNode != null &amp;&amp; box.BoxNode.BoxChildren != null &amp;&amp; box.BoxNode.BoxChildren.Count &gt; 0) { CreateMenuTree(box.BoxNode, indent + indent); } } } </code></pre> <p>Here I also created a fully workable code: <a href="https://gist.github.com/PeterStegnar/5127896" rel="nofollow">Gist code for this question</a>*</p> <p>Please note for the MVC scenario of course you replace the Console.WriteLine with the proper url link generation and indent with some kind CSS class. But I guess you should get the point.</p> <p>*Please note that this is not a production code, but a DEMO one.</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