kb_ kb_ - 22 days ago 5
C# Question

iterate through objects with Lists of the object

I have a small program which should create a simple menu.
My current problem is that i have a object which should fill the main menu point and then all under menu points.
My question is, a IList can have a second or third IList and I have really no idea how to interate over n ILists

Example:

MainNodeObj:
NodeDtoId = 1,
ItemCode = 'A'
IList<NodeDTO> ChildMenuNodes
{
MainNodeObj:
NodeDtoId = 2,
ItemCode = '2',
IList<NodeDTO> ChildMenuNodes
{
MainNodeObj:
NodeDtoId = 3,
ItemCode = '3',
}


My problem is that each ChildNode can have a new childnode and for each child node i will create a new object...sounds easy but i dont know how to iterate over n new childnodes

Methods:

private IEnumerable<NodeDTO> SortedNodes(int id)
{
var nodes = LoadMenuNodes(id);
foreach (MenuNode menuNode in nodes
.Where(s => s.MenuItemId == null && s.ParentNodeId == null)
.OrderBy(x => x?.Sequence))
{
NodeDTO tmpMenuNode = new NodeDTO();
tmpMenuNode.MenuNodeDtoId = menuNode.Id;
tmpMenuNode.MenuItemCode = menuNode.MenuItem?.Code;
tmpMenuNode.ChildMenuNodes = LoadChildNodes(menuNode.ChildMenuNodes).ToList();
yield return tmpMenuNode;
}
}
private IEnumerable<NodeDTO> LoadChildNodes(MenuNodeList menuNode)
{
foreach (MenuNode childNode in menuNode)
{
NodeDTO tmChildNode = new NodeDTO();
tmChildNode.MenuNodeDtoId = childNode.Id;
tmChildNode.MenuItemCode = childNode?.MenuItem?.Code;
tmChildNode.ChildMenuNodes = null;
yield return tmChildNode;
}
}



public class NodeDTO
{
public int NodeDtoId { get; set; }
public string ItemCode { get; set; }
public IList<NodeDTO> ChildMenuNodes { get; set; }
}

Answer

Can't you just use a resursive function

By placing this in the LoadChildNodes function.

tmpChildNode.ChildMenuNodes = LoadChildNodes(childNode.ChildMenuNodes).ToList();