Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
293 views
in Technique[技术] by (71.8m points)

c# - Recursive reading of List<Object>

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
  • First

Is there a way to do this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Maybe take a look at the TreeView control? http://msdn.microsoft.com/en-us/library/7a9swst5(v=vs.80).aspx

The ASP.NET TreeView control is designed to present users with data in a hierarchical structure. Users can open individual nodes that can in turn contain child nodes. The TreeView control is suitable for displaying XML data, but can be used for any data that can be represented in a hierarchy.

I think it will be what you want.

Otherwise, it's a matter of iterating through each item in your list and recursively processing each sub-item which may or may not have more sub-items. It's tricky, but only at first.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...