Simon
Simon

Reputation: 125

different ways to get TreeNode Count

In C# there are different ways of getting the Count of TreeNodes of a parent node:

    int numberOfNodes = node.Nodes.OfType<TreeNode>().Count();
    int numberOfNodes = node.Nodes.Count;

I know that count refers to a property of a List and Count() is a method on the IEnumerable (given from TypeOf) to get its count. My Question is, whether there are any differences. Aren't all nodes of a TreeNode always of type TreeNode? Is it advised to use one over the other in some cases or is the first option just some possibility which is useful for other scenarios and also would work for the node count problem. The Reason I ask is because I have seen both in code I read and don't know whats better.

Edit: I am talking about the TreeNodes from Windows Forms: https://msdn.microsoft.com/de-de/library/system.windows.forms.treenode(v=vs.110).aspx

Upvotes: 1

Views: 4582

Answers (2)

goldgalaxy
goldgalaxy

Reputation: 41

Source: Youtube

C# TreeView SampleCode

        private void Form1_Load(object sender, EventArgs e)
        {
            label1.Text = "Node : " + GetChildNodesCount(treeView1.Nodes) ;
        }

        private int GetChildNodesCount(TreeNodeCollection nodes)
        {
            int nodeC = nodes.Count ;

            foreach(TreeNode node in nodes)
            {
                nodeC += GetChildNodesCount(node.Nodes) ;
            }
            return nodeC ;
        }

Upvotes: 0

mjwills
mjwills

Reputation: 23898

int numberOfNodes = node.Nodes.OfType<TreeNode>().Count();
int numberOfNodes = node.Nodes.Count;

Of those two options, the second is faster - since it doesn't involve the overhead of involving LINQ.

Also consider using GetNodeCount as an alternative, especially if you are interested in the count of the entire sub tree.

Upvotes: 3

Related Questions