简体   繁体   English

如何使用linq查询获取层次数据的深度?

[英]How to get depth of hierarchical data with linq query?

I have a list of hierarchical data like this: 我有一个像这样的分层数据列表:

var list = new List<Data>(){some data...}

class Data
{
    public int number;
    public List<Data> info;
}

Note: Data in leaf of tree --> info = null 注意:树的叶子中的数据 - > info = null

Example: 例:

numbers are number property of Data class numbers是Data类的number property

   --1
      --11
   --2
      --21
      --22
      --23
      --24
   --3
      --31
      --32
          --321
          --322
   --4
      --41
      --42

How to know max depth of tree with linq query(Not Recursive method or for loop ) to list of data? 如何通过linq查询(非递归方法或for循环)知道树的最大深度到数据列表?

in this example max level is 3 for 321,322 在此示例中,321,322的最大级别为3

Thanks. 谢谢。

LINQ and SQL operate on flat data structures; LINQ和SQL在平面数据结构上运行; they are not designed for recursive data structures. 它们不是为递归数据结构而设计的。

With LINQ to Entities, I believe you're out of luck. 有了LINQ to Entities,我相信你运气不好。 Store the depth of the subtree in each node and recursively update it whenever you insert/delete a node. 将子树的深度存储在每个节点中,并在插入/删除节点时以递归方式更新它。

With LINQ to Objects, you could define a recursive extension method that returns all paths in a tree and take the length of the longest path: 使用LINQ to Objects,您可以定义一个递归扩展方法,该方法返回树中的所有路径并获取最长路径的长度:

var result = root.Paths().Max(path => path.Length);

where 哪里

public static IEnumerable<Data[]> Paths(this Data data)
{
    return Paths(data, new[] { data });
}

private static IEnumerable<Data[]> Paths(Data data, Data[] path)
{
    return new[] { path }.Concat((data.info ?? Enumerable.Empty<Data>())
    .SelectMany(child => Paths(child, path.Concat(new[] { child }).ToArray())));
}

All Linq operators use a loop in some way so it is not possible to solve with linq if the requirement is no loop. 所有Linq运算符都以某种方式使用循环,因此如果需求不是循环,则无法使用linq求解。

It is possible without recursion. 没有递归就有可能。 You just need a stack. 你只需要一个堆栈。 Something like 就像是

public static IEnumerable<Tuple<int, T>> FlattenWithDepth<T>(T root, Func<T, IEnumerable<T>> children) {
    var stack = new Stack<Tuple<int, T>>();

    stack.Push(Tuple.Create(1, root));

    while (stack.Count > 0) {
        var node = stack.Pop();

        foreach (var child in children(node.Item2)) {
            stack.Push(Tuple.Create(node.Item1+1, child));
        }
        yield return node;
    }
}

Your linq query will then be 那么您的linq查询将是

FlattenWithDepth(root, x => x.info ?? Enumerable.Empty<Data>()).Max(x => x.Item1);

(sorry don't have a compiler available to verify) (抱歉,没有可用于验证的编译器)

** Edit. **编辑。 Just saw that you had multiple roots ** 刚看到你有多个根**

list.SelectMany(y => FlattenWithDepth(y, x => x.info ?? Enumerable.Empty<Data>()))
    .Max(x => x.Item1)

The following would work: 以下将有效:

internal static class ListDataExtension
{
    public static int MaxDepthOfTree(this List<Data> dataList)
    {
        return dataList.Max(data => data.MaxDepthOfTree);
    }
}
internal class Data
{
    public int number;
    public List<Data> info;

    public int MaxDepthOfTree
    {
        get 
        { 
            return GetDepth(1); 
        }
    }

    int GetDepth(int depth)
    {
        if (info == null)
            return depth;
        var maxChild = info.Max(x => x.GetDepth(depth));
        return maxChild + 1;
    }
}

Then just call: 然后打电话:

var maxDepth = list.MaxDepthOfTree();

If you should use it in DB, I would suggest add additional column to your DB to save the depth of tree, there are some situation which depth changes: 如果你应该在DB中使用它,我建议在你的数据库中添加额外的列来保存树的深度,有一些深度变化的情况:

  1. Adding new element, its depth is FatherDepth + 1. 添加新元素,其深度为FatherDepth + 1。
  2. Delete: If this is cascade relation there is no problem with deleting, but if it's not cascade you should write a recursive query to update children's depth. 删除:如果这是级联关系,则删除没有问题,但如果不是级联,则应编写递归查询以更新子级深度。

For finding depth just run a query to find the maximum depth value. 要查找深度,只需运行查询以查找最大深度值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM