1

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

3 Answers 3

1

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
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.