c# – LINQ在树视图中获取最深层节点
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了c# – LINQ在树视图中获取最深层节点,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1727字,纯文字阅读大概需要3分钟。
内容图文
![c# – LINQ在树视图中获取最深层节点](/upload/InfoBanner/zyjiaocheng/823/a354b210afae4a54839267fcf7ced3b8.jpg)
假设我有一个WinForms Treeview,如下所示:
Parent1
Child1
Sub-Child1
DeepestNode1
DeepestNode2
DeepestNode3
Sub-Child2
DeepestNode4
DeepestNode5
DeepestNode6
Child2
Sub-Child3
Sub-Child4
Sub-Child5
Sub-Child6
Child3
(no children)
我想创建一个函数:
Function GetDeepestChildren(MyNode as Treenode) as List(Of Treenode)
在哪里,如果结果如下:
GetDeepestChildren(Parent1) = {DeepestNode1, DeepestNode2, DeepestNode3, DeepestNode4, DeepestNode5, DeepestNode6}
GetDeepestChildren(Sub-Child1) = {DeepestNode1, DeepestNode2, DeepestNode3}
GetDeepestChildren(Child2) = {Sub-Child3, Sub-Child4, Sub-Child5, Sub-Child6}
GetDeepestChildren(Child3) = Empty list
…换句话说,总是从给定的节点进入最深层次并返回子节点 – 即使它们在不同的父节点之间分开(如Parent1中的情况).
我创建了一个函数,它会告诉我节点的深度是多少,如下所示:
Public Function GetDeepestChildNodeLevel(ByVal ParentNode As TreeNode) As Integer
Dim subLevel = ParentNode.Nodes.Cast(Of TreeNode).Select(Function(subNode) GetDeepestChildNodeLevel(subNode))
Return If(subLevel.Count = 0, 0, subLevel.Max() + 1)
End Function
所以我知道从什么程度来得到孩子,我正在寻找的是一个可以做到这一点的功能 – Somethign的行:
Function GetDeepestChildren(MyNode as Treenode) as List(Of Treenode)
Return All child nodes where level = GetDeepestChildNodeLevel(MyNode)
End function
我希望这是有道理的 – 谢谢!
解决方法:
在C#中,您可以使用yield return或递归lambda来完成.以下是第二种方法的示例:
Func<TreeNode,IEnumerable<TreeNode>> getChildren = null;
getChildren = n => {
if (n.Nodes.Count != 0) {
var list = new List<TreeNode>(n.Nodes.Where(c => c.Nodes.Count == 0));
foreach (var c in n.Nodes) {
// Note the recursive call below:
list.AddRange(getChildren(c));
}
return list;
} else {
return new TreeNode[0];
}
};
var res = getChildren(myTree);
内容总结
以上是互联网集市为您收集整理的c# – LINQ在树视图中获取最深层节点全部内容,希望文章能够帮你解决c# – LINQ在树视图中获取最深层节点所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。