Recursive Hierarchical Parent child
.net, algorithm, c#, linq
Solution
You could use this approach:
- Get all the items from the database (without filling the SubItems).
- Build a `Lookup<int?,Item>` of parent ids and items with that parent id.
- 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();
Problem
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 int id{get;set;} public string Name{get;set;} public int? ParentId{get;set;} public List<Item> SubItems{get;set;} } ``` I want to build a hierarchical structure of Items from the collection. Assume a collection is 100 items from which I need to construct the structure based on the ParentId mapping. I tried this post Recursive Hierarchical Joins in C# and LINQ but it gives me an error if ParentId is null. Also tried Build tree type list by recursively checking parent-child relationship C# , but this solution also does not work for me. How do I achieve this?