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?
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:
This creates a single list, and adds items to it as it goes.
One point though – if you’ve already got the child
Categoryobjects, do you really need to callGetagain? Does each child only contain its ID until you fetch the whole category?