Recursive Hierarchy - Recursive Query using Linq

c# entity-framework linq recursion

Question

To map to a recursive structure, I'm using Entity Framework (version 6), and it maps well.

My problem is that I'm trying to recursively get all of a certain node's ALL child nodes.

I can simply obtain the child nodes using Linq.

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

Does anyone have knowledge of a clear implementation that will obtain all children recursively?

1
25
7/9/2018 12:06:08 PM

Accepted Answer

This tree structure can be traversed using a recursive technique, but you can also use an explicit stack to avoid using the stack space, which isn't always enough for huge tree structures. This will function better as well because such a method is also extremely pleasant as an iterator block, and iterator blocks are far less expensive when recursive than standard methods:

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);
    }
}
58
6/25/2015 3:08:44 PM

Popular Answer

ZZZ_tmp


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow