根据 1,2,2,3,1,2,2 规则 生成一个 菜单树

此项功能是在读取word的时候 根据标题层级分出父子关系菜单

具体效果

image

递归实现
using System;
using System.Collections.Generic;

public class Menu
{
    public int Id { get; set; }
    public int Pid { get; set; }
    public string Name { get; set; }
    public List<Menu> Children { get; set; }
}

class Program
{
    static void Main()
    {
        int[] menuData = { 1, 2, 3, 3, 1, 2, 3, 4, 1, 2 };
        List<Menu> menus = GenerateMenu(menuData, 0, 0);

        foreach (var menu in menus)
        {
            PrintMenu(menu, 0);
        }
    }

    static List<Menu> GenerateMenu(int[] menuData, int startIndex, int parentId)
    {
        List<Menu> menus = new List<Menu>();

        while (startIndex < menuData.Length)
        {
            int currentId = menuData[startIndex];
            if (currentId == 1)
            {
                Menu menu = new Menu { Id = currentId, Pid = parentId, Name = "Menu 1", Children = new List<Menu>() };
                startIndex++;
                menu.Children = GenerateSubMenu(menuData, ref startIndex, currentId);
                menus.Add(menu);
            }
            else
            {
                throw new Exception("Invalid menu data. Root menu should start with 1.");
            }
        }

        return menus;
    }

    static List<Menu> GenerateSubMenu(int[] menuData, ref int startIndex, int parentId)
    {
        List<Menu> subMenus = new List<Menu>();

        while (startIndex < menuData.Length && menuData[startIndex] > 1)
        {
            int currentId = menuData[startIndex];
            Menu menu = new Menu { Id = currentId, Pid = parentId, Name = $"Menu {currentId}", Children = new List<Menu>() };
            startIndex++;

            if (startIndex < menuData.Length && menuData[startIndex] > currentId)
            {
                menu.Children = GenerateSubMenu(menuData, ref startIndex, currentId);
            }

            subMenus.Add(menu);
        }

        return subMenus;
    }

    static void PrintMenu(Menu menu, int level)
    {
        Console.WriteLine(new string(' ', level * 2) + $"Id: {menu.Id}, Pid: {menu.Pid}, Name: {menu.Name}");
        foreach (var child in menu.Children)
        {
            PrintMenu(child, level + 1);
        }
    }
}

posted @ 2024-03-03 18:35  Bo-Hong  阅读(4)  评论(0编辑  收藏  举报