gpt4 book ai didi

.net - 如何使用LINQ to Entity选择递归嵌套实体

转载 作者:行者123 更新时间:2023-12-04 02:57:07 24 4
gpt4 key购买 nike

我有一个名为Category的实体,该实体包含一个名为ChildCategories的IEnumerable。类别可以具有这些子类别,也可以具有自己的子类别,依此类推。

假设我已经选择了顶级父类别,我想获得所有子类别及其子类别,依此类推,以便获得该类别的所有层次子类别。我希望这是flat花一现,并返回初始类别。我尝试创建类似

    public static IEnumerable<T> AllChildren<T>(this IEnumerable<T> items, 
Func<T, IEnumerable<T>> children, bool includeSelf)
{
foreach (var item in items)
{
if (includeSelf)
{
yield return item;
}
if (children != null)
{
foreach (var a in children(item))
{
yield return a;
children(a).AllChildren(children, false);
}
}
}
}

使用SelectMany方法后,它会变得扁平,但是还没有完全理解它。

最佳答案

在他的博客文章Traverse a hierarchical structure with LINQ-to-Hierarchical中,Arjan Einbu描述了一种简化层次结构以便于查询的方法:

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<T> FlattenHierarchy<T>(this T node, 
Func<T, IEnumerable<T>> 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以及尝试使用LINQ直接遍历层次结构时固有的问题。

关于.net - 如何使用LINQ to Entity选择递归嵌套实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5422735/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com