Get list of all checked nodes and its subnodes in treeview

前端 未结 3 1573
陌清茗
陌清茗 2020-12-19 02:30

I have a treeview list check boxes and the list contains nodes, subnodes and in some cases subnode of subnode. When user check some items i want to get list of selected item

3条回答
  •  温柔的废话
    2020-12-19 02:57

    If you like LINQ, you can create an extension method that traverses the whole treeview:

    internal static IEnumerable Descendants(this TreeNodeCollection c)
    {
        foreach (var node in c.OfType())
        {
            yield return node;
    
            foreach (var child in node.Nodes.Descendants())
            {
                yield return child;
            }
        }
    }
    

    Then you can perform every operations you want using LINQ. In your case, getting a list of selected nodes is easy:

    var selectedNodes = myTreeView.Nodes.Descendants()
                        .Where(n => n.Checked)
                        .Select(n => n.Text)
                        .ToList();
    

    An advantage of this approach is it is generic.

    However, because the Descendant() method traverses the whole tree, it might be a bit less efficient than the answer given by @mybirthname because it only cares about nodes that are checked with their parents. I dont known if your use case includes this constraint.

    EDIT: Now @mybirthname answer has been edited, it is doing the same. Now you have the loop and the LINQ solution, both are recursive.

提交回复
热议问题