[英]Recursively search nested lists
I've read and searched and I'm yet to figure out an answer to this relatively simple issue.我已经阅读并搜索过,但我还没有找到这个相对简单问题的答案。
I have a class:我有一个 class:
public class AccessibleTreeItem
{
public string name;
public List<AccessibleTreeItem> children;
public AccessibleTreeItem()
{
children = new List<AccessibleTreeItem>();
}
}
which is populate using a series of functions that don't really matter in this context, but what I'm looking for is a way to search through ALL of the children items in the list, searching for a particular 'name' value, and if found, returning that List.这是使用一系列在这种情况下并不重要的函数填充的,但我正在寻找的是一种搜索列表中所有子项的方法,搜索特定的“名称”值,以及如果找到,则返回该列表。
How is this achieved in the easiest manner, with the least performance hit?这是如何以最简单的方式实现的,对性能的影响最小? Thanks - I've been stumped at this point for days now...
谢谢 - 我已经被难住了好几天了......
public class AccessibleTreeItem
{
public string name;
public List<AccessibleTreeItem> children;
public AccessibleTreeItem()
{
children = new List<AccessibleTreeItem>();
}
public static AccessibleTreeItem Find(AccessibleTreeItem node, string name)
{
if (node == null)
return null;
if (node.name == name)
return node;
foreach (var child in node.children)
{
var found = Find(child, name);
if (found != null)
return found;
}
return null;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.