2011-08-25 59 views
1

在asp.net应用程序中,我有一个类别对象列表,在此列表中,每个类别可以是另一个类别的父类别。使用列表的递归方法

例子:

catid 1 catname cat1 parentid null 
catid 2 catname cat2 parentid null 
catid 3 catname cat3 parentid 2 
catid 4 catname cat4 parentid 2 
catid 5 catname cat5 parentid 4 
catid 6 catname cat6 parentid 5 
catit 7 catname cat7 parentid 5 

我想写通过分类列表循环的方法,翻出父类别,并获取列表中的子类别。 这样做很容易,我遇到的困难部分是如何知道递归方法中何时到达最后一个类别对象。

这就是我要找

protected void load_categories(ref List<category> list, category item) 
{ 
    //loop through list and match item ID with list item parent ID 
    //loop through child items of category item using load_categories() 
    //HOW DO I STOP ONCE EVERYTHING IS DONE? 
} 

回答

1

我会这么做:

List<category> categoryWithParents = new List<category>(); 
protected void load_categories(List<category> list, category item) 
{ 
    foreach(category cat in list) 
    { 
     if(item.id == cat.id) 
     { 
     categoryWithParents.Add(cat); 
     if(cat.parentid != null) //if category has parent 
      load_categories(list, cat); //load that parent 
     break; //adding break should stop looping because we found category 
     } 
    } 
} 

当您拨打类别catid 5 catname cat5 parentid 4 categoryWithParents列表应包含(加入顺序)的方法:

catid 5 catname cat5 parentid 4  
catid 4 catname cat4 parentid 2 
catid 2 catname cat2 parentid null 
0

逻辑你可以通过周围的当前项目的索引,而指数小于列表中的项目的数量只会继续。

0

我想你有这样

results = new empty results 

For childItem in list 
    if (childItem.parentId == item.id) 
      results.add (loadCategories(list, item) 
    else 
      // nothing to do 

return results 

一些代码,所以你的递归停止用刚掉出来,这是别的=>无关