Back to Devexpress

How to: Iterate through nodes and calculate the number of nodes at a specific level

windowsforms-5626-controls-and-libraries-tree-list-examples-nodes-how-to-iterate-through-nodes-and-calculate-the-number-of-nodes-at-a-specific-level.md

latest2.5 KB
Original Source

How to: Iterate through nodes and calculate the number of nodes at a specific level

  • Nov 13, 2018
  • 2 minutes to read

The following example shows how to use the Nodes Iterator to obtain the number of nodes which reside on the specified nesting level.

In the example, a CustomNodeOperation object is created that is used to calculate this number. The operation class contains an internal counter that is incremented by one each time a node that resides at the specified nesting level is accessed.

To get the total number of the nodes which reside at the specified nesting level, a CustomNodeOperation instance is created and passed to the TreeListNodesIterator.DoLocalOperation method. After the method has been performed, the CustomNodeOperation.NodeCount property is read to get the number of nodes.

csharp
using DevExpress.XtraTreeList.Nodes;
using DevExpress.XtraTreeList.Nodes.Operations;

// Declaring the custom operation class.
class CustomNodeOperation : TreeListOperation {
   int level;
   int nodeCount;
   public CustomNodeOperation(int level) : base() {
      this.level = level;
      this.nodeCount = 0;
   }
   public override void Execute(TreeListNode node) {
      if(node.Level == level)
         nodeCount++;
   }
   public int NodeCount {
      get { return nodeCount; }
   }
}

// ...

CustomNodeOperation operation = new CustomNodeOperation(2);
treeList1.NodesIterator.DoLocalOperation(operation, treeList1.Nodes);
int totalNodesAtSecondLevel = operation.NodeCount;
vb
Imports DevExpress.XtraTreeList.Nodes
Imports DevExpress.XtraTreeList.Nodes.Operations

' Declaring the custom operation class.
Class CustomNodeOperation
    Inherits TreeListOperation
    Private level As Integer
    Private nodeCountCore As Integer

    Public Sub New(ByVal level As Integer)
        Me.level = level
        Me.nodeCountCore = 0
    End Sub 'New

    Public Overrides Sub Execute(ByVal node As TreeListNode)
        If node.Level = level Then
            nodeCountCore += 1
        End If
    End Sub 'Execute

    Public ReadOnly Property NodeCount() As Integer
        Get
            Return nodeCountCore
        End Get
    End Property
End Class

'...

Dim operation As CustomNodeOperation = New CustomNodeOperation(2)
TreeList1.NodesIterator.DoLocalOperation(operation, TreeList1.Nodes)
Dim totalNodesAtSecondLevel As Integer = operation.NodeCount