15

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

Rami Alshareef
  • 7,015
  • 12
  • 47
  • 75

4 Answers4

46

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();
JLRishe
  • 99,490
  • 19
  • 131
  • 169
18

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.

Sarin
  • 1,255
  • 11
  • 14
1

I have required such functionality and compare both methods and find method 2nd is faster than 1st :), right now in my database cards or records are limited but 1st method taking 4 times more time to complete.

may be this can help for those who are conscious about time.

1 method


    public JsonResult CardData()
    {
        var watch = System.Diagnostics.Stopwatch.StartNew();
        OrgChartWithApiContext db = new OrgChartWithApiContext();

        var items = db.Cards.ToList();
        Action<Card> 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<Card> hierarchicalItems = items
            .Where(rootItem => !rootItem.ParentId.HasValue)
            .ToList();

        //Call the SetChildren method to set the children on each root level item.
        hierarchicalItems.ForEach(SetChildren);
        watch.Stop();
        var timetaken = watch.ElapsedMilliseconds;

        return new JsonResult() { Data = hierarchicalItems, ContentType = "Json", JsonRequestBehavior = JsonRequestBehavior.AllowGet };
    }

method 2


    public JsonResult Card2Data()
    {
        var watch = System.Diagnostics.Stopwatch.StartNew();
        OrgChartWithApiContext db = new OrgChartWithApiContext();
        var items = db.Cards.ToList();
        List<Card> topItems = items.Where(item => !item.ParentId.HasValue).ToList();
        topItems.ForEach(item => item.Children = items.Where(child => child.ParentId == item.id).ToList());
        watch.Stop();
        var timetaken = watch.ElapsedMilliseconds;
        return new JsonResult() { Data = topItems, ContentType = "Json", JsonRequestBehavior = JsonRequestBehavior.AllowGet };
    }
arjthakur
  • 61
  • 6
0

For those who are looking for a more generic approach that is very quick and easy to use. I have made some generic interfaces and extension methods that will quickly sort and return hierarchical data.

public interface IHierarchicalData<TData>
{
    public IHierarchicalData<TData>? Parent { get; set; }
    public IList<IHierarchicalData<TData>> Children { get; set; }
    public TData? Data { get; set; }
}

public class DefaultHierarchy<TData> : IHierarchicalData<TData>
{
    public IHierarchicalData<TData>? Parent { get; set; }
    public IList<IHierarchicalData<TData>> Children { get; set; } = new List<IHierarchicalData<TData>>();
    public TData? Data { get; set; }        
}

public static class HierarchyExtensions
{
    public static IEnumerable<THierarchyModel> CreateHierarchy<THierarchyModel, TData, TId>(this IEnumerable<TData> flatList, Func<TData, TId> idSelector, Func<TData, TId?> parentIdSelector)
        where THierarchyModel : IHierarchicalData<TData>, new()
    {
        var lookup = flatList.Select(f => new THierarchyModel { Data = f })
                                                       .Where(item => item.Data is not null)
                                                       .ToDictionary(h => idSelector(h.Data));

        foreach (var item in lookup.Values)
        {
            var parentId = parentIdSelector(item.Data);
            if (parentId is null || !lookup.TryGetValue(parentId, out var parent))
            {
                yield return item;
                continue;
            }

            parent.Children.Add(item);
            item.Parent = parent;
        }
    }

    public static IEnumerable<IHierarchicalData<TData>> CreateHierarchy<TData, TId>(this IEnumerable<TData> flatList, Func<TData, TId> idSelector, Func<TData, TId?> parentIdSelector)
    {
        return flatList.CreateHierarchy<DefaultHierarchy<TData>,TData, TId>(idSelector, parentIdSelector);
    }
}

Usage is very simple. All you have to do is pass in the func to get the parentId and Id of the item. Then you can traverse the hierarchy and get the information you need by accessing the "Data" property.

private IEnumerable<IHierarchicalData<TestHierarchy>> hierarchyData 
     => testHierarchy.CreateHierarchy(t => t.Id, t => t.ParentId);

private class TestHierarchy
{
    public int Id { get; set; }     
    public int? ParentId { get; set; }
    public string Name { get; set; }
}

private List<TestHierarchy> testHierarchy = new()
    {
        new() { Id = 1, ParentId = null, Name = "Top Level 1" },
            new() { Id = 2, ParentId = 1, Name = "Top Level 1.1" },
            new() { Id = 3, ParentId = 1, Name = "Top Level 1.2" },
                new() { Id = 12, ParentId = 3, Name = "Top Level 1.2.1" },
            new() { Id = 10, ParentId = 1, Name = "Top Level 1.3" },
            new() { Id = 11, ParentId = 1, Name = "Top Level 1.4" },
        new() { Id = 4, ParentId = null, Name = "Top Level 2" },
            new() { Id = 5, ParentId = 4, Name = "Top Level 2.1" },
            new() { Id = 6, ParentId = 4, Name = "Top Level 2.2" },
            new() { Id = 7, ParentId = 4, Name = "Top Level 2.3" },
                new() { Id = 13, ParentId = 7, Name = "Top Level 2.3.1" },
                    new() { Id = 14, ParentId = 13, Name = "Top Level 2.3.1.1" },
            new() { Id = 8, ParentId = 4, Name = "Top Level 2.4" },
        new() { Id = 9, ParentId = null, Name = "Top Level 3" },
    };

Image of the above code