LINQ在树视图中获取最深层次的节点

Joh*_*tos 5 c# linq vb.net

假设我有一个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)
Run Code Online (Sandbox Code Playgroud)

我想创建一个函数:

Function GetDeepestChildren(MyNode as Treenode) as List(Of Treenode)
Run Code Online (Sandbox Code Playgroud)

在哪里,如果结果如下:

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
Run Code Online (Sandbox Code Playgroud)

...换句话说,总是从给定的节点进入最深层次并返回孩子 - 即使他们在不同的父母之间分开(如同的情况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
Run Code Online (Sandbox Code Playgroud)

所以我知道从什么程度来得到孩子,我正在寻找的是一个可以做到这一点的功能 - Somethign的行:

Function GetDeepestChildren(MyNode as Treenode) as List(Of Treenode)
       Return All child nodes where level = GetDeepestChildNodeLevel(MyNode)
End function
Run Code Online (Sandbox Code Playgroud)

我希望这是有道理的 - 谢谢!

das*_*ght 4

在 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);
Run Code Online (Sandbox Code Playgroud)