I need to build an nth level hierarchical list from a flat list.
I tried to play around with the solution in this answer: https://stackoverflow.com/a/167168/2127 , but I was not able to get the correct results.
Here is my object structure:
public class Group { public string Id { get; set; } public string Name { get; set; } public string ParentId { get; set; } public List<Group> Children { get; set; } } public List<Group> BuildGroupHierarchy(List<Group> groups) { var lookup = groups.Where(x => x.ParentId != null).ToList().ToLookup(c => c.ParentId); List<string> idsToRemove = new List<string>(); foreach (var c in groups) { if (c.Children == null) c.Children = new List<Group>(); if (lookup.Contains(c.Id)) c.Children.AddRange(lookup[c.Id].ToList()); } return groups; }
This is a virtual hierarchical structure present in flat:
But this is what I get, basically the second level is repeated:
Haris
source share