递归菜单生成器C#

时间:2012-07-12 20:49:29

标签: c# .net recursion

我需要为课程列表网站构建面包/路径

例如,课程有不同的菜单项,我需要显示如下

  • CHAPTER01 /
  • CHAPTER01 / Lesson01 /
  • CHAPTER01 / Lesson01 / Exam01 /
  • Chapter01 / Lesson01 / Exam01 / Question 03 /
  • Chapter01 / Lesson01 / Exam01 / Question 04 / Item 01
  • CHAPTER01 / Lesson02 /
  • Chapter02
  • Chapter02 / Lesson01

上面只是一个如何将项目安排在路径中的示例

为了得到这个,我有项目清单

Public Class Item
{
    public string Level
    {
        get;
        set;
    }

    public string Title
    {
        get;
        set;
    }
}

列表可以创建如下

IList<Item> Items = new List<Item>();
Items.Add (new Item {Level = "0", Title = "Chapter01"});
Items.Add (new Item {Level = "1", Title = "Lesson01"});
Items.Add (new Item {Level = "2", Title = "Exam01"});
Items.Add (new Item {Level = "3", Title = "Question 03"});
Items.Add (new Item {Level = "3", Title = "Question 04"});
Items.Add (new Item {Level = "4", Title = "Item 01"});
Items.Add (new Item {Level = "1", Title = "Lesson02"});

Items.Add (new Item {Level = "0", Title = "Chapter02"});
Items.Add (new Item {Level = "1", Title = "Lesson01"});

父项的级别始终为0,子级将具有1,2,3等...

任何人都可以让我在C#中提出一个递归函数来实现这个

1 个答案:

答案 0 :(得分:2)

我上次这样做的方法是将菜单项实际组合成菜单项。例如:

public class MenuItem{
    public string Caption {get; set;}
    public int Level {get; set; }
    public List<MenuItem> MenuItems {get; set;}
    public MenuItem(string caption){
        Caption = caption;
        MenuItems = new List<MenuItem>();
    }
}

然后,当您构建菜单结构时,首先使用List<MenuItem>来保存顶级MenuItem对象,然后MenuItems.Add(new MenuItem("Question 1"))

构建层次结构后,可以使用以下内容输出它:

private void DisplyMenuStructure(List<MenuItems> menu){
    foreach(MenuItem currentItem in menu){
        if (currentItem.MenuItems.Count>0){
            DisplayMenuStructure(currentItem.MenuItems);
        } else {
            Console.WriteLine(currentItem.Caption);
        }
    }
}

要填充层次结构,请使用以下内容:

public void BuildMenumStructure(){
    //Instantiate a File menu
    MenuItem root = new MenuItem("File");
    root.Level = 0;
    //Add some menu items
    root.MenuItems.Add(new MenuItem("New"){Level = 1});
    root.MenuItems.Add(new MenuItem("Edit"){Level = 1});
    //Build a save menu and add it in
    MenuItem saveMenu = new MenuItem("Save");
    saveMenu.MenuItems.Add(new MenuItem("Save As"){Level = 2});
    saveMenu.MenuItems.Add(new MenuItem("Save"){Level = 2});
    root.MenuItems.Add(saveMenu);
}