Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

(ID/ParentID) list to Hierarchical list

MyClass consists of ID ParentID and List<MyClass> as Children

I have list of MyClass like this

ID  ParentID
1   0
2   7
3   1
4   5
5   1
6   2
7   1
8   6
9   0
10  9

Output (Hierarchical list) as List<MyClass>

1 __ 3
 |__ 5__ 4
 |__ 7__ 2__ 6__ 8
     |__ 11

9 __10

What is the simplest way to achieve this in linq?
P.S.: ParentID not sorted

Edit:
My try:

class MyClass
{
    public int ID;
    public int ParentID;
    public List<MyClass> Children = new List<MyClass>();
    public MyClass(int id, int parent_id)
    {
        ID = id;
        ParentID = parent_id;
    }
}

initialize sample data and try to reach hierarchical data

 List<MyClass> items = new List<MyClass>()
{
    new MyClass(1, 0), 
    new MyClass(2, 7), 
    new MyClass(3, 1), 
    new MyClass(4, 5), 
    new MyClass(5, 1), 
    new MyClass(6, 2), 
    new MyClass(7,1), 
    new MyClass(8, 6), 
    new MyClass(9, 0), 
    new MyClass(10, 9), 
    new MyClass(11, 7), 
};

Dictionary<int, MyClass> dic = items.ToDictionary(ee => ee.ID);

foreach (var c in items)
    if (dic.ContainsKey(c.ParentID))
        dic[c.ParentID].Children.Add(c);

as you can see, lots of items I don't want still in the dictionary

like image 239
Rami Alshareef Avatar asked Feb 23 '12 07:02

Rami Alshareef


2 Answers

Recursion is not necessary here if you build the parent-child relationships before filtering. Since the members of the list remain the same objects, as long as you associate each member of the list with its immediate children, all of the necessary relationships will be built.

This can be done in two lines:

items.ForEach(item => item.Children = items.Where(child => child.ParentID == item.ID)
                                           .ToList());
List<MyClass> topItems = items.Where(item => item.ParentID == 0).ToList();
like image 168
JLRishe Avatar answered Oct 21 '22 19:10

JLRishe


For hierarchical data, you need recursion - a foreach loop won't suffice.

Action<MyClass> SetChildren = null;
SetChildren = parent =>
    {
        parent.Children = items
            .Where(childItem => childItem.ParentID == parent.ID)
            .ToList();

        //Recursively call the SetChildren method for each child.
        parent.Children
            .ForEach(SetChildren);
    };

//Initialize the hierarchical list to root level items
List<MyClass> hierarchicalItems = items
    .Where(rootItem => rootItem.ParentID == 0)
    .ToList();

//Call the SetChildren method to set the children on each root level item.
hierarchicalItems.ForEach(SetChildren);

items is the same list you use. Notice how the SetChildren method is called within itself. This is what constructs the hierarchy.

like image 40
Sarin Avatar answered Oct 21 '22 18:10

Sarin