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?
The simplest solution seems to introduce a recursive method. You can't get recursive just by LINQ itself:
If you have lazy loading, then this should work:
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 less expensive when recursive than regular methods, so this will perform better as well:
Thanks Servy, I expanded on your code a bit to allow for iterating single items, as well as collections. I came across when looking for a way to find out if an exception or any inner exceptions were of a certain type, but this will have many uses.
Here is a fiddle with examples, test cases, etc. dotnetfiddle LinqTraversal
Just the helpers:
I like more the linq way to do recursive.