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?