'displaying parent-child elements hierarchically in c#

I have a parent-child structure in my db and I want to list them hierarchically n a C# program:

id  text  parentid

1   A     NULL
2   B     NULL
5   a1    1
6   b1    2
9   a11   5
10  a12   5
11  b12   6

Class:

 public class Category
    {

        public int id { get; set; }       
        public string text{ get; set; }     
        public int? ParentId { get; set; }        
        public List<Category> children;

    }

This is my attempt to create nested list:

List<Category> cats = new List<Category>();
while (sdr.Read())
{
     Category c = new Category();
     //filling class list from db
     cats.Add(c);
}
var child=cats.ToLookup(cat=>cat.ParentId );
foreach (var cat in cats)
     cat.children=child[cat.id].ToList();

json output of above code:

[{"children":[{"children":[{"children":[],"id":9,"text":"a11","ParentId":5},{"children":[],"id":10,"text":"a12","ParentId":5}],"id":5,"text":"a1","ParentId":1}],"id":1,"text":"A","ParentId":null},{"children":[{"children":[{"children":[],"id":11,"text":"b12","ParentId":6}],"id":6,"text":"b1","ParentId":2}],"id":2,"text":"B","ParentId":null},{"children":[{"children":[],"id":9,"text":"a11","ParentId":5},{"children":[],"id":10,"text":"a12","ParentId":5}],"id":5,"text":"a1","ParentId":1},{"children":[{"children":[],"id":11,"text":"b12","ParentId":6}],"id":6,"text":"b1","ParentId":2},{"children":[],"id":9,"text":"a11","ParentId":5},{"children":[],"id":10,"text":"a12","ParentId":5},{"children":[],"id":11,"text":"b12","ParentId":6}]

The problem is the above code represents all ids at the same level. It repeats child elements putting them at the same level (root items).

This is the expected output:

[{
        "children": [{
            "children": [{
                "children": [],
                "id": 9,
                "text": "a11",
                "ParentId": 5
            }, {
                "children": [],
                "id": 10,
                "text": "a12",
                "ParentId": 5
            }],
            "id": 5,
            "text": "a1",
            "ParentId": 1
        }],
        "id": 1,
        "text": "A",
        "ParentId": null
    }, {
        "children": [{
            "children": [{
                "children": [],
                "id": 11,
                "text": "b12",
                "ParentId": 6
            }],
            "id": 6,
            "text": "b1",
            "ParentId": 2
        }],
        "id": 2,
        "text": "B",
        "ParentId": null
    }]

How to achieve this structure by code?



Solution 1:[1]

You could use a recursive method, starting with items without a parent id:

var categories = new List<Category>();

GetCategories(ref categories);

void GetCategories(ref List<Category> categories, int? parentId = null)
{
    string query = string.Empty; 

    if (parentId.HasValue)
    {
        query = "SELECT * FROM categories WHERE parentid=@parentid";         
    }
    else
    {
        query = "SELECT * FROM categories WHERE parentid IS NULL";
    }

    using (var conn = new SqlConnection(connStr))
    {
        using (var command = new SqlCommand(query, conn))
        {
            conn.Open();

            if (parentId.HasValue)
            {
                command.Parameters.AddWithValue("@parentid", parentId.Value);
            }

            using (var reader = command.ExecuteReader())
            {
                while (reader.Read())
                {
                   var c = new Category();
                   c.text = reader["text"];
                   //etc..
                   categories.Add(c);
                   c.children = new List<Category>();
                   GetCategories(ref c.children, c.id);
                }
            }
        }
   }
}

Solution 2:[2]

Try this

    var allCategories = new List<Category>();

After fetching data...

    var children = allCategories.ToLookup(cat => cat.ParentId);
    foreach (var category in allCategories)
    {
        category.Children = children[category.ParentId].ToList();
    }

Solution 3:[3]

Flat List to Hierarchy

public class TreeObject
  {
     public int ID { get; set; }
     public int ParentID { get; set; }
     public string Name { get; set; }
     public List<TreeObject> Children { get; set; } = new List<TreeObject>();
  }

Send flat list to this method and get hierarchy (parent/child) object list

public List<TreeObject> FlatToHierarchy(List<TreeObject> list)
        {
           
            var lookup = new Dictionary<int, TreeObject>();
            var nested = new List<TreeObject>();

            foreach (TreeObject item in list)
            {
                if (lookup.ContainsKey(item.ParentID))
                {
                    // add to the parent's child list 
                    lookup[item.ParentID].Children.Add(item);
                }
                else
                {
                    // no parent added yet (or this is the first time)
                    nested.Add(item);
                }
                lookup.Add(item.ID, item);
            }

            return nested;
        }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 NaDeR Star
Solution 3 Md. Nazmul Nadim