Searching a tree using LINQ

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)

Leave a Comment