递归获取ID
哈啰!
我有一个 List
其中 Channel
是一个自定义类 offcourse:
public class Channel
{
public long ID { get; set; }
public long parentID { get; set; }
}
strcuture 可以是这样的:
ID = 1, parentID = 0
ID = 64, parentID = 1
ID = 28, parentID = 64
ID = 36, parentID = 64
ID = 5, parentID = 0
等等。
我想做的是获取特定频道的所有儿童 ID:
function List<long> getChildrenIDS (long ID)
{
// WHAT GOES HERE?
}
haloa!
i have a List<Channel>
where Channel
is a custom class offcourse:
public class Channel
{
public long ID { get; set; }
public long parentID { get; set; }
}
strcuture can be something like:
ID = 1, parentID = 0
ID = 64, parentID = 1
ID = 28, parentID = 64
ID = 36, parentID = 64
ID = 5, parentID = 0
and so on.
what i would like to do is get all children ID's of a specific channel:
function List<long> getChildrenIDS (long ID)
{
// WHAT GOES HERE?
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
要获取所有子项:
将其构建为返回
IEnumerable
,而不是返回List
,然后调用需要List的代码。
可以使用new List(GetChildren(list, id))
或GetChildren(list, id).ToList()
,而调用不需要此功能的代码时,可以通过不构建实际上不需要的列表来获得更好的内存性能和获得第一个结果的时间,如foreach( GetChildren(list, id)) 中的长 childID
。要获得所有后代(孩子、孙子、曾孙等),这是我们可以使用递归(根据您的问题标题)的唯一情况,请使用:
假设不能重复(通过多个路由的同一个孙子):
如果可能有重复,那么您可以将
.Distinct()
应用于上面,或者选择:这就是说,我可能宁愿通过让 Channel 类维护一个来对此进行建模子项
List
。To get all children:
Build this as returning an
IEnumerable<long>
rather than returning aList<long>
as then calling code that needs aList<long>
can use eithernew List<long>(GetChildren(list, id))
orGetChildren(list, id).ToList()
, while calling code that doesn't need this can get better performance in memory and time to first result by not building a list it doesn't actually need, as inforeach(long childID in GetChildren(list, id))
.To get all descendants (children, grandchildren, great-grandchildren, etc.) which is the only case we could make any use of recursion (as per your question title) use:
Assuming there cannot be duplicates (same grandchild through multiple routes):
If there can be duplicates then you could apply
.Distinct()
to the above, or go for:This said, I would probably rather model this by having the Channel classes maintain a
List<Channel>
of children.不知道 Marcos 的答案是否真的产生了所需的结果,但我会以更 LINQish 的方式编写:
如果您还需要深层嵌套的,您可能可以使用此函数:
但请注意,它不会检查循环冗余并可能最终导致 stackoverflow 异常!
Don't know if Marcos answer really produces the desired result, but i would write this in a more LINQish fashion:
If you also need the deep nested ones you could maybe use this function:
But be aware that it doesn't check for cyclic redundancy and could end up in an stackoverflow exception!
在
你的班级中,你可以这样做:
没有递归(所以只有孩子)
或有递归(孩子的孩子也是如此)
Having
in your class, you can do:
No recursion (so only children)
or with recursion (children of children too)