LINQ recursion function?

LINQ doesn’t really “do” recursion nicely. Your solution seems appropriate – although I’m not sure HasChildren is really required… why not just use an empty list for an item with no children?

An alternative is to write a DescendantsAndSelf method which will return all of the descendants (including the item itself), something like this;

// Warning: potentially expensive!
public IEnumerable<SomeItem> DescendantsAndSelf()
{
    yield return this;
    foreach (var item in Children.SelectMany(x => x.DescendantsAndSelf()))
    {
        yield return item;
    }
}

However, if the tree is deep that ends up being very inefficient because each item needs to “pass through” all the iterators of its ancestry. Wes Dyer has blogged about this, showing a more efficient implementation.

Anyway, if you have a method like this (however it’s implemented) you can just use a normal “where” clause to find an item (or First/FirstOrDefault etc).

Leave a Comment