I have to build a nth-level hierarchical list from a flat list.
I have tried to play around with the solution in this answer: https://stackoverflow.com/a/25532561 but I have not been able to get proper 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 the virtual hierarchical structure present in flat one:
- Group 1
- Group 1-1
- Group 2
- Group 2-1
- Group 2-1-1
- Group 2-2
- Group 2-1
But this is what I am getting, basically second level has been repeated:
- Group 1
- Group 1-1
- Group 2
- Group 2-1
- Group 2-1-1
- Group 2-2
- Group 2-1
- Group 2-1
- Group 2-1-1