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

递归实现
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);
}
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)