I have an entity called Category and the entity contains a IEnumerable called ChildCategories. A category can have these child categories which can have it\'s own child cate
In his blog post Traverse a hierarchical structure with LINQ-to-Hierarchical , Arjan Einbu describes a method of flattening hierarchies for ease of querying:
Can I make a generic extension method that will flatten any hierarchy? [...]
To do that, we need to analyze which parts of the method needs to be swapped out. That would be the TreeNode’s Nodes property. Can we access that in an other way? Yes, I think a delegate can help us, so lets give it a try:
public static IEnumerableFlattenHierarchy (this T node, Func > getChildEnumerator) { yield return node; if(getChildEnumerator(node) != null) { foreach(var child in getChildEnumerator(node)) { foreach(var childOrDescendant in child.FlattenHierarchy(getChildEnumerator)) { yield return childOrDescendant; } } } }
casperOne describes this in his answer as well, along with the problems inherent in trying to traverse the hierarchy directly using LINQ.