[英]How to get depth of hierarchical data with linq query?
我有一个像这样的分层数据列表:
var list = new List<Data>(){some data...}
class Data
{
public int number;
public List<Data> info;
}
注意:树的叶子中的数据 - > info = null
例:
numbers是Data类的number property
--1
--11
--2
--21
--22
--23
--24
--3
--31
--32
--321
--322
--4
--41
--42
如何通过linq查询(非递归方法或for循环)知道树的最大深度到数据列表?
在此示例中,321,322的最大级别为3
谢谢。
LINQ和SQL在平面数据结构上运行; 它们不是为递归数据结构而设计的。
有了LINQ to Entities,我相信你运气不好。 将子树的深度存储在每个节点中,并在插入/删除节点时以递归方式更新它。
使用LINQ to Objects,您可以定义一个递归扩展方法,该方法返回树中的所有路径并获取最长路径的长度:
var result = root.Paths().Max(path => path.Length);
哪里
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())));
}
所有Linq运算符都以某种方式使用循环,因此如果需求不是循环,则无法使用linq求解。
没有递归就有可能。 你只需要一个堆栈。 就像是
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;
}
}
那么您的linq查询将是
FlattenWithDepth(root, x => x.info ?? Enumerable.Empty<Data>()).Max(x => x.Item1);
(抱歉,没有可用于验证的编译器)
**编辑。 刚看到你有多个根**
list.SelectMany(y => FlattenWithDepth(y, x => x.info ?? Enumerable.Empty<Data>()))
.Max(x => x.Item1)
以下将有效:
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;
}
}
然后打电话:
var maxDepth = list.MaxDepthOfTree();
如果你应该在DB中使用它,我建议在你的数据库中添加额外的列来保存树的深度,有一些深度变化的情况:
要查找深度,只需运行查询以查找最大深度值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.