当前位置: 首页 > 编程语言 > C#

递归调用返回一个List,返回类型导致我的问题Share

时间:2023-04-10 14:32:57 C#

递归调用返回一个List,返回类型导致我的问题子类别。所以它看起来像:publicListGetAllChildCats(intcategoryid){Listlist=newList>Category>();类别c=Get(categoryid);foreach(Categorycatinc.ChildCategories){list.Add(GetAllChildCats(cat.CategoryID))}}这失败了,因为对list.add的调用需要一个类别对象,但它返回另一个列表,我应该如何解决这个问题?目前你没有显示任何实际上将单个类别添加到列表中的东西......我假设你想在递归Preet的解决方案肯定有效时添加Get(categoryId)的结果,但这里有一个避免创建All的替代方法附加列表:publicListGetAllChildCats(intcategoryId){Listret=newList();GetAllChildCats(categoryId,ret);返还;}privatevoidGetAllChildCats(intcategoryId,Listlist){类别c=Get(categoryid);列表.添加(c);foreach(c.ChildCategories中的类别猫){GetAllChildCats(cat.CategoryID,列表);这将创建一个列表并向其中添加项目。但有一件事——如果您已经有了子Category对象,您真的需要再次调用Get吗?在获取整个类别之前,每个孩子是否仅包含其id?foreach(Categorycatinc.ChildCategories){list.AddRange(GetAllChildCats(cat.CategoryID))}不要忘记返回列表;我认为这个linq版本可以让您避免创建列表的开销:publicIEnumerableGetAllChildCats(intcategoryid){Categoryc=Get(categoryid);returnnew[]{c}.Concat(c.ChildCategories.SelectMany(cat=>GetAllChildCats(cat)));如果需要,您始终可以在返回的IEnumerable上调用ToList()。我以前有同样的问题。这就是我解决它的方法:publicvoidGetAllChildCategories(ProductCategoryParentCategory){foreach(ParentCategory.ChildCategories中的产品类别猫){GetAllChildCategories(猫);JonSkeet对C#7的回答修改版):以上是C#学习教程:递归调用返回一个List,返回类型引出我的问题分享的全部内容,如果对大家有用需要了解一下更多关于C#学习教程,希望大家多多关注—publicListGetAllChildCats(introotId){Listlist=newList();遍历(rootId);返回列表;voidTraverse(intcategoryId){类别c=Get(categoryId);列表.Add(c);foreach(c.ChildCategories中的类别猫){Traverse(cat.CategoryID);}}}本文收集自网络,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如需转载请注明出处: