1

I'm building an application with MVC4 that handles Boxes. A Box can contain many boxes and may contain a Box. The menu should look like this:

> Box 1
> Box 2
   > Box 2.A
   > Box 2.B
   > Box 2.C
      > Box 2.C.1
   > Box 2.D
> Box 3

Right now I have the following:

public object GetTree(Box? box){

   foreach (var box in box.Boxes)
   {
       GetTree(box)
       // append menu item with box.name, box.id pair so a link can get generated
   }

I'm a little bit stuck though. The menu will get passed as an object to a client, which will somehow display it as a tree menu of links. What data structure is most appropriate here?

1

1 Answer 1

1

Here is all about recursion and a proper data structure.

So here is all about recursion. You already started implementing that way, so this is good.

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 Box object. Lets now enhance it. Create a BoxNode object that have a List of Boxes, like so:

public class BoxNode
{
    public List<Box> BoxChildren 
    {
        get; set;
    }
}

Then Box:

public class Box
{
    public string Name
    {
        get; set;
    }

    public BoxNode BoxNode
    {
        get; set;
    }
}

So now we have the basic data structure, lets go to the function:

    public static void CreateMenuTree(BoxNode boxNode, string indent)
    {
        foreach (Box box in boxNode.BoxChildren)
        {
            Console.WriteLine(indent + box.Name);

            if (box.BoxNode != null && box.BoxNode.BoxChildren != null && box.BoxNode.BoxChildren.Count > 0)
            {
                CreateMenuTree(box.BoxNode, indent + indent);
            }
        }
    }  

Here I also created a fully workable code: Gist code for this question*

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.

*Please note that this is not a production code, but a DEMO one.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.