I am using C# language. My problem is that i don’t know how to store my retrieved hierarchical result set to my object.
Here’s is my Object:
public class CategoryItem
{
public string Name { get; set; }
public int CategoryID { get; set; }
public int ParentID { get; set; }
public List<CategoryItem> SubCategory = new List<CategoryItem>();
public List<CategoryItem> GetSubCategory()
{
return SubCategory;
}
public void AddSubCategory(CategoryItem ci)
{
SubCategory.Add(ci);
}
public void RemoveSubCategory(CategoryItem ci)
{
for (int i = 0; i < SubCategory.Count; i++)
{
if (SubCategory.ElementAt(i).CategoryID == ci.CategoryID)
{
SubCategory.RemoveAt(i);
break;
}
}
}
}
Here’s is my sample retrieve data set from MSSQL server
ID PrntID Title
_______ _______
1 0 Node1
2 1 Node2
3 1 Node3
4 2 Node4
5 2 Node5
6 2 Node6
7 3 Node7
8 4 Node8
9 4 Node9
10 9 Node10
Tree view for easy reference
Node 1
-Node 2
--Node 4
---Node 8
---Node 9
----Node 10
--Node 5
--Node 6
-Node 3
--Node 7
My problem is how to do I store this result to my “CategoryItem Object”. I don’t have any clue do I need to use iteration for this? Specially when the node is 2 level-deep.
I want to store it in such a like this:
List<CategoryItem> items = new List<CategoryItem>();
with this I can dig every objects in the ‘items’ object and I can access its sub-category / child / children using the GetSubCategory() method of my class. Is this possible?
If you know that in your DataSet a node will never appear before its parent, you can use this code. Here you keep track of the already read items in a Dictionary when you can look for parents of the newly read nodes. If you find the parent you add the new item to its children, otherwise it’s a first level node.
If my assumption isn’t true (i.e. it is possible for a node to appear in the DataSet before its parent), you have to first read all the nodes (and put them in the Dictionary), then loop through the same Dictionary to build the result. Something like this: