建设有MVC4递归树菜单 - 要使用的数据结构? [英] Building a Tree menu with recursion in MVC4 - which data structure to use?

查看:120
本文介绍了建设有MVC4递归树菜单 - 要使用的数据结构?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在建设有MVC4处理盒的应用程序。一个盒子里可以包含许多箱子,可能包含一个盒子。菜单应该是这样的:

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?

推荐答案

因此​​,这里是所有关于递归。你已经开始实施的方式,所以这是很好的。

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.

首要的事情。数据结构。要重新present树像你应该建立树形喜欢的对象菜单,所以你必须创建它们的简单图。您开局不错。你有一个对象。现在,让我们增强了。创建具有盒的列表, BoxNode 对象,像这样:

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;
    }
}

然后

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);
            }
        }
    }  

在这里,我还创建了一个完全可行的code:吉斯特code本题 *

请注意,当然你用正确的网址链接生成和缩进某种CSS类取代Console.WriteLine命令的MVC场景。不过,我想你应该明白了吧。

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.

*请注意,这不是一个生产code,但一个DEMO之一。

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

这篇关于建设有MVC4递归树菜单 - 要使用的数据结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆