Recursive call return a List, return type causing me issues

Viewed 24672

I have a recursive method that returns categories, and checks for its sub categories.

This is my code:

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 GetAllChildCats() returns List<Category>

How should I work around this?

5 Answers

Here's a modified version of Jon Skeet's answer using a local method (C# 7) :

    public List<Category> GetAllChildCats(int rootId)
    {
        List<Category> list = new List<Category>();
        Traverse(rootId);
        return list;

        void Traverse(int categoryId)
        {
            Category c = Get(categoryId);
            list.Add(c);

            foreach (Category cat in c.ChildCategories)
            {
                Traverse(cat.CategoryID);
            }
        }
    }
Related