mattgcon
mattgcon

Reputation: 4848

Recursive method using List

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

Upvotes: 1

Views: 12209

Answers (3)

Renatas M.
Renatas M.

Reputation: 11820

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

Upvotes: 1

djna
djna

Reputation: 55897

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

Upvotes: 0

Xhalent
Xhalent

Reputation: 3944

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.

Upvotes: 0

Related Questions