Accessing all the nodes in TreeView Control

前端 未结 7 1607
小蘑菇
小蘑菇 2020-11-27 22:27

I have a TreeView Control with set of nodes and child nodes. For example:

ROOT has A,B,C.

A has a1, a2, a3 and then

7条回答
  •  旧时难觅i
    2020-11-27 22:57

    I know this thread is quite old and my method doesn't exactly reduce the amount of recursion and it may be slightly slower but it makes my code a bit cleaner.

    I use an extension method for IEnumarable<> to flatten any tree (not just TreeView nodes):

    public static IEnumerable Flatten(
        this IEnumerable rootNodes, 
        Func> childrenFunction)
    {
        return rootNodes.SelectMany(
            child => new[] { child }
                .Concat((childrenFunction(child) ?? Enumerable.Empty())
                .Flatten(childrenFunction)));
    }
    

    I then use this method to get all the nodes of the tree:

    IEnumerable allNodes = treeView1.Nodes.Cast()
        .Flatten(n => n.Nodes.Cast());
    

提交回复
热议问题