Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursive method to convert flat collection to hierarchal collection?

I have been stuck on this problem for a few days and would appreciate some ideas or help in resolving it. I have a collection of objects

 public class Hierarchy
{
    public Hierarchy(string iD, string name, int level, string parentID, string topParent)
    {
        ID = iD;
        Name = name;
        Level = level;
        ParentID = parentID;
        Children = new HashSet<Hierarchy>();
    }
    public string ID { get; set; }
    public string Name{ get; set; }
    public int Level { get; set; }
    public string ParentID { get; set; }
    public ICollection<Hierarchy> Children { get; set; }
}

The data from the Linq Query to my Entity is:

ID      Name     Level ParentID
295152  name1    1     null
12345   child1   2     295152
54321   child2   2     295152
44444   child1a  3     12345
33333   child1b  3     12345
22222   child2a  3     54321
22221   child2b  3     54321
22002   child2c  3     54321
20001   child2a2 4     22222
20101   child2b2 4     22222

This data could extend to an unknown depth of levels (I'm only showing 4). Ultimately I would have one Hierarchy object with a collection of multiple child objects which in turn may have a collection of multiple child objects...etc... There will always only be one top level object.

I am trying to use Linq as much as possible in this project.

This obviously needs some sort of recursive method but I'm stuck. Any ideas or help would be appreciated.

TIA

like image 279
John S Avatar asked Jan 11 '13 04:01

John S


1 Answers

You can try this recursive function:

void PopulateChildren(Hierarchy root, ICollection<Hierarchy> source)
{
    foreach (var hierarchy in source.Where(h => h.ParentID == root.ParentID))
    {
        root.Children.Add(hierarchy);
        PopulateChildren(root, source);
    }
}

Which you can use like this:

ICollection<Hierarchy> hierarchies = new List<Hierarchy>(); // source

// Get root
var root = hierarchies.Single(h => h.Level == 1);

// Populate children recursively
PopulateChildren(root, hierarchies);
like image 180
OJ Raqueño Avatar answered Sep 19 '22 14:09

OJ Raqueño