递归调用返回害我的问题的列表,返回类型 [英] Recursive call return a List, return type causing me issues
问题描述
我有一个递归方法,它返回我的类别,并检查它的子类。
I have a recursive method that is return me categories, and checking for its sub categories.
因此,它看起来像:
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) )
}
}
这将失败,因为list.add通话期望一个类别对象,但它是返回另一个列表中,我应该怎么解决此问题?
推荐答案
目前你有没有什么这实际上增加了一个单独的类别列表中显示...我假设你递归,要添加获取的
的结果(的categoryId),以及·
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.
有一点,但 - 如果你已经有了孩子类别
的对象,你真的需要再次获取
打电话?请问,直到获取全品类每个孩子只包含其ID?
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?
这篇关于递归调用返回害我的问题的列表,返回类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!