Recursive Hierarchical Parent child

前端 未结 3 1828
遇见更好的自我
遇见更好的自我 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 01:47

    You could use this approach:

    1. Get all the items from the database (without filling the SubItems).
    2. Build a Lookup of parent ids and items with that parent id.
    3. Loop through the items and associate each item with the subitems using the lookup.

    Code:

    var items = // get from the database... (e.g. as a list)
    var lookup = items.ToLookup(x => x.ParentId);
    foreach (var item in items)
        item.SubItems = lookup[item.Id].ToList();
    

    As @EamonNerbonne commented below, you can get the root elements as well, if you need to:

    var roots = lookup[null].ToList();
    

提交回复
热议问题