Iterate recursively through nodes in a tree view?

后端 未结 2 1603
闹比i
闹比i 2021-02-09 15:41

I have a tree view which is populated already with files/folders from another procedure. I would like to iterate one by one through the items in the tree view, going in exact or

2条回答
  •  情深已故
    2021-02-09 16:24

    In fact you can use a for loop.

    var
      Node: TTreeNode;
    ....
    for Node in TreeView.Items do
      DoSomething(Node);
    

    This is syntactic sugar for:

    for i := 0 to TreeView.Items.Count-1 do
      DoSomething(TreeView.Items[i]);
    

    In terms of readability I would recommend the for/in loop.

    In older Delphi versions that don't support the node iterator you may prefer to do it with a while loop.

    Node := TreeView.Items.GetFirstNode;
    while Assigned(Node) do
    begin
      DoSomething(Node);
      Node := Node.GetNext;
    end;
    

    I expect there are other ways to do it. These are the only ones that I know!


    LU RD makes the interesting observation that the documentation states:

    Accessing tree view items by index can be time-intensive, particularly when the tree view contains many items. For optimal performance, try to design your application so that it has as few dependencies on the tree view's item index as possible.

    This is quite true. For random access the code has to walk the tree, starting at the root, until the ith node is located.

    However, there is an optimisation for sequential access. The Delphi tree view wrapper remembers the index of the last node located by index. The next time you ask for a node with index no more than one different from the cached node, the required node can be returned quickly. This is implemented in TTreeNodes.GetNodeFromIndex.

提交回复
热议问题