-2

Trying to query child item of same object to n-depth and display in the below format. So for each sub cat add tab space.

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; }
}

Create item,

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"}
                        } },
                    }  }, 
                }
            };

I have below code, which is not complete. it can go only two depth

item.childItems.ForEach(i => {
                Console.WriteLine(i.label);
                i.childItems.ForEach(i1 =>
                {
                    Console.WriteLine("\t" + i1.label);
                });
            });
Ahelp
  • 183
  • 4
  • 13
  • Your "LINQ query" doesn't use any LINQ methods, in addition to only traversing to a depth of 2. It also doesn't even emulate a LINQ style of programming. – Servy Jul 25 '18 at 17:44

2 Answers2

1

I don't think you can write just a LINQ query to achieve what you want since the depth is not known beforehand, so you will need to write a recursive function that traverses the tree.

Ilya Chernomordik
  • 27,817
  • 27
  • 121
  • 207
1

Yes, as the first answer indicates, this requires recursion.

Display(item, 0);

void Display(NavItem item, Int32 tabs)
{
    Console.WriteLine($"{new String('\t', tabs)}{item.label}");
    if (item.childItems != null)
    {
        foreach (var child in item.childItems)
        {
            Display(child, tabs + 1);
        }
    }
}
Carlo Bos
  • 3,105
  • 2
  • 16
  • 29