Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursive call return a List, return type causing me issues

Tags:

c#

recursion

I have a recursive method that is return me categories, and checking for its sub categories.

So it looks like:

public List<Category> GetAllChildCats(int categoryid)
{
      List<Category> list = new List>Category>();

      Category c = Get(categoryid);

      foreach(Category cat in c.ChildCategories)
      {
              list.Add( GetAllChildCats(cat.CategoryID) )

      }

}

This fails because the call to list.add expects a Category object, but it is return yet another List, how should I work around this?

like image 922
mrblah Avatar asked Oct 01 '09 13:10

mrblah


2 Answers

Currently you haven't shown anything which actually adds a single category to the list... I'm assuming that as you recurse, you want to add the results of Get(categoryId) as well·

Preet's solution will certainly work, but here's an alternative which avoids creating all the extra lists:

public List<Category> GetAllChildCats(int categoryId)
{
    List<Category> ret = new List<Category>();
    GetAllChildCats(categoryId, ret);
    return ret;
}

private void GetAllChildCats(int categoryId, List<Category> list)
{
    Category c = Get(categoryid);
    list.Add(c);

    foreach(Category cat in c.ChildCategories)
    {
        GetAllChildCats(cat.CategoryID, list);
    }
}

This creates a single list, and adds items to it as it goes.

One point though - if you've already got the child Category objects, do you really need to call Get again? Does each child only contain its ID until you fetch the whole category?

like image 53
Jon Skeet Avatar answered Sep 28 '22 07:09

Jon Skeet


   foreach(Category cat in c.ChildCategories)
      {
              list.AddRange( GetAllChildCats(cat.CategoryID) )

      }

and don't forget the

return list;
like image 34
Preet Sangha Avatar answered Sep 28 '22 06:09

Preet Sangha