(ID/ParentID) list to Hierarchical list

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

MyClass consists of ID ParentID and List as Children

I have list of MyClass

3条回答
  •  醉话见心
    2020-12-05 06:32

    For hierarchical data, you need recursion - a foreach loop won't suffice.

    Action SetChildren = null;
    SetChildren = parent =>
        {
            parent.Children = items
                .Where(childItem => childItem.ParentID == parent.ID)
                .ToList();
    
            //Recursively call the SetChildren method for each child.
            parent.Children
                .ForEach(SetChildren);
        };
    
    //Initialize the hierarchical list to root level items
    List hierarchicalItems = items
        .Where(rootItem => rootItem.ParentID == 0)
        .ToList();
    
    //Call the SetChildren method to set the children on each root level item.
    hierarchicalItems.ForEach(SetChildren);
    

    items is the same list you use. Notice how the SetChildren method is called within itself. This is what constructs the hierarchy.

提交回复
热议问题