MyClass consists of ID ParentID and List as Children
I have list of MyClass
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.