2

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

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-1
Community
  • 1
  • 1
Haris
  • 691
  • 3
  • 19
  • 34
  • Hello, no need for all this .. you could try to use SqlHierarchyId by adding the Microsoft.SqlServer.Types dll. Try to make a little search about it .. if you didn't understand how to use it just tell me. Im building in my project a xml using this SqlHierarchyId in c#. – Elie M Feb 11 '15 at 12:41
  • @Elie'Lebanon I am not using SQL Server so I cannot add its dlls in the solution. – Haris Feb 11 '15 at 12:45
  • No need to use sql server ! Im not using it too . You could use this dll normaly and use this property like other property in c# . – Elie M Feb 11 '15 at 12:50

0 Answers0