递归搜索嵌套列表 [英] Recursively search nested lists

查看:54
本文介绍了递归搜索嵌套列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经阅读并搜索过,但还没有找到解决这个相对简单问题的答案.

I've read and searched and I'm yet to figure out an answer to this relatively simple issue.

我有一堂课:

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;
    }
}

这篇关于递归搜索嵌套列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆