A very simple and highly efficient way to do this conversion is to create a search in which you map the identifier values ββto the nodes, which should be children of this identifier value. This search can be created in a single pass through the nodes. After that, you can iterate over all the nodes, again assigning their child collection the value of their identifier in the search.
Note that this is easier if the search is mapped to objects of the type you are converting to, and not to conversion.
var lookup = list.Categories .Select(category => new Category() { ID = category.ID, Name = category.Name, ParentID = category.ParentID, }) .ToLookup(category => category.ParentID); foreach (var category in lookup.SelectMany(x => x)) category.ChildCategories = lookup[category.ID].ToList(); var newList = new HieraricalCategoryList() { Categories = lookup[null].ToList(), };
Servy
source share