Creating a hierarchical structure from a flat list

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:

  • Group 1
    • Group 1-1
  • Group 2
    • Group 2-1
      • Group 2-1-1
    • Group 2-2

But this is what I get, basically the second level is repeated:

  • Group 1
    • Group 1-1
  • Group 2
    • Group 2-1
      • Group 2-1-1
    • Group 2-2
  • Group 2-1
    • Group 2-1-1
0
c # linq
source share

No one has answered this question yet.

See similar questions:

7
Matching a flat list to a hierarchical list with C # parent identifiers

or similar:

1786
How to create an Excel file (.XLS and .XLSX) in C # without installing Microsoft Office?
1658
Get int value from enum in C #
1270
Why not inherit from List <T>?
1266
How to update GUI from another thread?
826
Creating an array of bytes from a stream
747
Creating a comma separated list from IList <string> or IEnumerable <string>
640
How to create a new instance of an object from a Type
610
Using LINQ to remove items from a <T> list
eighteen
LINQ sort flat list based on childorder
0
C # hierarchy list (tree) to flatt list

All Articles