I have an object of a custom type I’ve made (Menu) which can contain child elements of the same type, which naturally can contain child elements and so on.
I wish to generate menus and submenus out of these objects, but I’m wondering how I can traverse them recursively so that I don’t have to hard code all my loops. I am a stranger to recursion, is anyone able to shed some light on how to traverse the Menu object and all the underlying objects?
Example code:
public class Menu {
public int MenuID { get; set; }
public int Name { get; set; }
public Menu[] _ChildMenus { get; set; }
}
Here is one option:
If you need to know how “deep” each menu is nested you can add a level parameter: