How do I select recursive nested entities using LINQ to Entity

后端 未结 3 1496
臣服心动
臣服心动 2020-12-31 12:56

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

3条回答
  •  一个人的身影
    2020-12-31 13:43

    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 IEnumerable FlattenHierarchy(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.

提交回复
热议问题