HeWhoWas
HeWhoWas

Reputation: 621

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:

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...

Upvotes: 6

Views: 13784

Answers (1)

Petar Ivanov
Petar Ivanov

Reputation: 93030

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

Upvotes: 22

Related Questions