(ID/ParentID) list to Hierarchical list

后端 未结 3 948
清酒与你
清酒与你 2020-12-05 05:47

MyClass consists of ID ParentID and List as Children

I have list of MyClass

3条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-05 06:19

    Recursion is not necessary here if you build the parent-child relationships before filtering. Since the members of the list remain the same objects, as long as you associate each member of the list with its immediate children, all of the necessary relationships will be built.

    This can be done in two lines:

    items.ForEach(item => item.Children = items.Where(child => child.ParentID == item.ID)
                                               .ToList());
    List topItems = items.Where(item => item.ParentID == 0).ToList();
    

提交回复
热议问题