开发者

Recursive method using List

开发者 https://www.devze.com 2023-03-30 09:30 出处:网络
Within an asp.net application I have a list of categories objects, within this list each category can be a parent of another category.

Within an asp.net application I have a list of categories objects, within this list each category can be a parent of another category.

Example:

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

I want to write a method that loops through the list of categories, pulls out the parent categories and acquires the child categories from the list. Doing this is easy the hard part I am having problems with is how do I know when the last category object has been reached within a recursive method.

This is the logic I am looking for

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


I would do so:

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

when you call method with category catid 5 catname cat5 parentid 4 categoryWithParents list should contain(in adding order):

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


You could pass the index of the current item around and only continue while the index is less than the number of items in the list.


I suppose you have some code like this

 results = new empty results

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

 return results

so your recursion-stopping just falls out, it's the else => nothing to do

0

精彩评论

暂无评论...
验证码 换一张
取 消