C# 使用列表的递归方法

C# 使用列表的递归方法,c#,asp.net,list,recursion,C#,Asp.net,List,Recursion,在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

在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?
}
受保护的无效荷载\u类别(参考列表,类别项目)
{
//循环浏览列表并将项目ID与列表项目父ID匹配
//使用load_categories()遍历类别项的子项
//一旦一切都完成了,我该如何停止?
}

您可以传递当前项目的索引,并且只能在索引小于列表中的项目数时继续。

您可以传递当前项目的索引,并且只能在索引小于列表中的项目数时继续。

我想您有这样的代码

 results = new empty results

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

 return results

所以你的递归停止失败了,它是else=>没什么可做的

我想你有一些这样的代码

 results = new empty results

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

 return results
所以你的递归停止失败了,这是else=>没什么可做的

我会这么做:

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
       }
    }
}
我会这样做:

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
       }
    }
}