Home > database >  How to loop multiple ICollection use recursive (Backtracking)
How to loop multiple ICollection use recursive (Backtracking)

Time:09-29

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).

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

CodePudding user response:

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