1

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

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

  • 第01章/
  • Chapter01/Lesson01/
  • Chapter01/Lesson01/Exam01/
  • Chapter01/Lesson01/Exam01/问题03/
  • Chapter01/Lesson01/Exam01/问题04/项目01
  • Chapter01/Lesson02/
  • 第02章
  • 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# 中提出一个递归函数来实现这一点

4

1 回答 1

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);
}
于 2012-07-12T21:09:14.453 回答