C# 用于嵌套子litems n-depth c的Linq查询#

C# 用于嵌套子litems n-depth c的Linq查询#,c#,linq,C#,Linq,正在尝试将同一对象的子项查询到n-depth并以以下格式显示。因此,为每个子类别添加选项卡空间 Cat 1 Sub Cat 1 - 1 Sub Cat 1 - 2 Cat 2 Sub Cat 2 - 1 Sub Cat 2 - 2 Sub Cat 3 - 2 - 2 class NavItem { public string label { get; set; } public List<NavItem> childIte

正在尝试将同一对象的子项查询到n-depth并以以下格式显示。因此,为每个子类别添加选项卡空间

Cat 1
   Sub Cat 1 - 1
   Sub Cat 1 - 2
Cat 2
   Sub Cat 2 - 1
   Sub Cat 2 - 2
          Sub Cat 3 - 2 - 2

class NavItem {
    public string label { get; set; }
    public List<NavItem> childItems { get; set; }
}

我不认为您可以编写一个LINQ查询来实现您想要的,因为深度事先不知道,所以您需要编写一个遍历树的递归函数。

是的,正如第一个答案所示,这需要递归

显示(项目,0);
无效显示(NavItem项,Int32选项卡)
{
Console.WriteLine($“{newstring('\t',tabs)}{item.label}”);
if(item.childItems!=null)
{
foreach(item.childItems中的变量child)
{
显示(子项,选项卡+1);
}
}
}
您的“LINQ查询”不使用任何LINQ方法,只使用深度为2的遍历。它甚至没有模仿LINQ风格的编程。
var item = new NavItem()
            {
                label = "Root",
                childItems = new List<NavItem>() {
                    new NavItem() { label = "Cat 1" , childItems = new  List<NavItem>() {
                        new  NavItem() { label = "Sub Cat 1 - 1" },
                        new  NavItem() { label = "Sub Cat 1 - 2" },
                    } },
                    new NavItem() { label = "Cat 2", childItems = new  List<NavItem>() {
                        new  NavItem() { label = "Sub Cat 2 - 1" },
                        new  NavItem() { label = "Sub Cat 2 - 2", childItems = new List<NavItem>() {
                            new NavItem() { label = "Sub Cat 3 - 2 - 2"}
                        } },
                    }  }, 
                }
            };
item.childItems.ForEach(i => {
                Console.WriteLine(i.label);
                i.childItems.ForEach(i1 =>
                {
                    Console.WriteLine("\t" + i1.label);
                });
            });