Search code examples
c#recursionbacktrackingicollection

How to loop multiple ICollection use recursive (Backtracking)


Suppose class Menu use property ICollection<Menu> Items { get ; set ; } . It is representing data field in mongodb . When insert data and show it will have the following structure:

enter image description here

I want loop from N1 to N1-child1,child2,child3,.... (done).

Recursive N1

How to when N1 and its children are finished. Looping back to N2 , N3 .

Here is my json code according to mongodb structure:

enter image description here

enter image description here

I want to get the Id of branches N1 , N2 , N3 equivalent to Object1 and Object2 to compare with the passed ID parameter , if it matches , then stop the recursion


Solution

  • It's super simple. This is all you need:

    public IEnumerable<Menu> Traversal(Menu menu)
    {
        yield return menu;
        if (menu.Items != null)
            foreach (var x in menu.Items)
                foreach (var y in Traversal(x))
                    yield return y;
    }