Building hierarchy objects from flat list of parent/child

前端 未结 6 623
花落未央
花落未央 2021-01-30 18:07

I have a list of items in a hierarchy, and I\'m attempting to parse this list out into an actual hierarchy of objects. I\'m using modified pre-order tree traversal to store/iter

6条回答
  •  情书的邮戳
    2021-01-30 18:35

    Alternative version that compiles normally, I wasn't sure if there was a problem with the code above.

    private List FlatToHierarchy(List list) {
          // hashtable lookup that allows us to grab references to the parent containers, based on id
            Dictionary lookup = new Dictionary();
          // actual nested collection to return
          List nested = new List();
    
          foreach(Page item in list) {
            if (lookup.ContainsKey(item.parentId)) {
              // add to the parent's child list 
              lookup[item.parentId].children.Add(item); //add item to parent's childs list
              lookup.Add(item.pageId, item); //add reference to page in lookup table
            } else {
              // no parent added yet (or this is the first time)
              nested.Add(item);     //add item directly to nested list                
              lookup.Add(item.pageId, item); //add reference to page in lookup table
            }
          }
        return nested;
        }
    

提交回复
热议问题