I have this structure of List<Object>, to be specific it is a “CategoryItem” Object. Here’s my declaration of “CategoryItem” Object.
public class CategoryItem
{
public string Name { get; set; }
public int CategoryID {get; set;}
public int ParentID {get; set; }
public List<CategoryItem> SubCategory {get; set;}
}
Here’s my sample data structure:
[0] CategoryID: 249
Name: "WelcomeNC"
ParentID: 0
SubCategory: length=4
[0] CategoryID: 250
Name: "CNC"
ParentID: 249
SubCategory: length=0
[1] CategoryID: 251
Name: "Production"
ParentID: 249
SubCategory: length=0
[2] CategoryID: 252
Name: "Administrative"
ParentID: 249
SubCategory: length=1
[0] CategoryID: 261
Name: "NPower"
ParentID: 252
SubCategory: length=0
[3] CategoryID: 253
Name: "Help"
ParentID: 249
SubCategory: length=1
[0] CategoryID: 254
Name: "7"
ParentID: 253
SubCategory: length=1
[0] CategoryID: 255
Name: "CHLK"
ParentID: 254
SubCategory: length=0
[1] CategoryID: 111
Name: "First"
ParentID: 0
SubCategory: length=0
My problem is, how do I step in each and every ‘CategoryItem’ object of my declared:
List<CategoryItem> categoryItems = new List<CategoryItem>();
So that I can display it in an unordered list in html like this
- WelcomeNC
- CNC
- Production
- Administrative
- NPower
- Help
- 7
- CHLK
- 7
- First
Is there a way to do this?
If your CategoryItem doesn’t contain a list of its children (like in the first version of the question), I would first of all build a Dictionary that foreach CategoryID gives you all the subcategory items, then recursively print all your items using this dictionary and starting with the items with parent “0”. Assuming that Print is the instruction that print the data associated with your item, and that it takes as the only parameter the level of indentation, the code will look like this:
It’s not really object oriented, but this should give you a hint about the direction to follow.
EDIT:
I saw that you edited the question and that now you have added the SubCategory property. This makes things much simpler and you can simply do: