Search code examples
c#linqentity-frameworkrecursion

Recursive Hierarchy - Recursive Query using Linq


I am using Entity Framework (version 6) to map to a recursive hierarchy and it maps nicely.

My issue is that I want to recursively get ALL child nodes of a particular node in the hierarchy.

I get the child nodes quite easily using Linq:

var recursiveList = db.ProcessHierarchyItems
            .Where(x => x.id == id)
            .SelectMany(x => x.Children);

Does anybody know of a clean implementation, that will recursively get all children?


Solution

  • While it is possible to use a recursive method here, you can traverse this tree structure using an explicit stack instead to avoid using the stack space, which isn't always sufficient for large tree structures. Such a method is also very nice as an iterator block, and iterator blocks are much more expensive when recursive than regular methods, so this will perform better as well:

    public static IEnumerable<T> Traverse<T>(this IEnumerable<T> items, 
        Func<T, IEnumerable<T>> childSelector)
    {
        var stack = new Stack<T>(items);
        while(stack.Any())
        {
            var next = stack.Pop();
            yield return next;
            foreach(var child in childSelector(next))
                stack.Push(child);
        }
    }