Searching a tree using LINQ

I have a tree created from this class.

class Node
{
    public string Key { get; }
    public List<Node> Children { get; }
}

I want to search in all children and all their children to get the ones matching a condition:

node.Key == SomeSpecialKey

How can I implement it?


It's a misconception that this requires recursion. It will require a stack or a queue and the easiest way is to implement it using recursion. For sake of completeness I'll provide a non-recursive answer.

static IEnumerable<Node> Descendants(this Node root)
{
    var nodes = new Stack<Node>(new[] {root});
    while (nodes.Any())
    {
        Node node = nodes.Pop();
        yield return node;
        foreach (var n in node.Children) nodes.Push(n);
    }
}

Use this expression for example to use it:

root.Descendants().Where(node => node.Key == SomeSpecialKey)

If you want to maintain Linq like syntax, you can use a method to obtain all the descendants (children + children's children etc.)

static class NodeExtensions
{
    public static IEnumerable<Node> Descendants(this Node node)
    {
        return node.Children.Concat(node.Children.SelectMany(n => n.Descendants()));
    }
}

This enumerable can then be queried like any other using where or first or whatever.