Using this Node class , you can simply do this:
var flatListOfItems = GetItemsFromDatabase(); var rootNodes =Node<Item>.CreateTree(flatListOfItems, i => i.id, i => i.ParentId);
Your elements no longer need subitems because the Node class has children and a descendant property. (Also ancestors, brothers and sisters, level, etc.).
The CreateTree method results in 1 or more rootnodes. If you are sure that there is always one rootnode, you can do rootNodes.Single () to get root.
source share