Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursively search nested lists

Tags:

c#

list

recursion

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

I have a 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...

like image 226
HeWhoWas Avatar asked Jul 02 '11 09:07

HeWhoWas


1 Answers

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;
    }
}
like image 193
Petar Ivanov Avatar answered Oct 11 '22 11:10

Petar Ivanov