我有一个递归方法,它返回我的类别,并检查其子类别.
所以它看起来像:
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) )
}
}
Run Code Online (Sandbox Code Playgroud)
这失败了,因为对list.add的调用需要一个Category对象,但它又返回另一个List,我应该如何解决这个问题呢?
Jon*_*eet 44
目前你没有显示任何实际上在列表中添加单个类别的内容...我假设你在递归时,你想要添加结果Get(categoryId)·
Preet的解决方案肯定会有效,但这里有一个替代方案可以避免创建所有额外的列表:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
这将创建一个列表,并在其中添加项目.
但有一点 - 如果你已经有了孩子的Category对象,你真的需要Get再次打电话吗?在您获取整个类别之前,每个孩子是否只包含其ID?
Pre*_*gha 12
foreach(Category cat in c.ChildCategories)
{
list.AddRange( GetAllChildCats(cat.CategoryID) )
}
Run Code Online (Sandbox Code Playgroud)
别忘了
return list;
Run Code Online (Sandbox Code Playgroud)