Recursive Hierarchical Parent child

前端 未结 3 1825
遇见更好的自我
遇见更好的自我 2021-02-10 01:13

I have a collection of items coming from a database which has a parentid value or null.

Here is my class design:

public class Item
{
public          


        
3条回答
  •  说谎
    说谎 (楼主)
    2021-02-10 02:00

    Using this Node class you can simply do this:

    var flatListOfItems = GetItemsFromDatabase();
    var rootNodes =Node.CreateTree(flatListOfItems, i => i.id, i => i.ParentId);
    

    Your items doesn't need the subitems anymore because the Node class has a children and a descendants property. (Also ancestors, siblings, level etc.).

    The CreateTree method results in 1 or more rootnodes. If you are sure that there is always 1 rootnode, you can do rootNodes.Single() to get the root.

提交回复
热议问题