简体   繁体   中英

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

I prefer generic extensions to flatten tree style object

public static IEnumerable<T> Flatten<T>(this IEnumerable<T> source, Func<T,IEnumerable<T>> selector) 
{
    return source.SelectMany(o => selector(o).Flatten(selector)).Concat(source);
}

how to call :

// create a new list for the node
var nodes = new IEnumerable<NodeDTO>();

// add the root node
nodes.Add(rootNode); // add the root node

// flatten the list
var flatList = = rootNode.Flatten(o=> o.ChildMenuNodes);

Can't you just use a resursive function

By placing this in the LoadChildNodes function.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM