/// <summary> /// Gets an enumerator over all the tree nodes /// </summary> /// <param name="treeView"></param> /// <returns></returns> public static IEnumerable<TreeNode> GetAllNodes(this TreeView treeView) { Stack<IEnumerator> enumerators = new Stack<IEnumerator>(); IEnumerator currentEnumerator = treeView.Nodes.GetEnumerator(); try { while (true) { // Is there still a node at this level ? if (currentEnumerator.MoveNext()) { // Retrieve the new current node TreeNode node = (TreeNode)currentEnumerator.Current; // Pushes the enumerator over its children if (node.Nodes.Count != 0) { enumerators.Push(currentEnumerator); currentEnumerator = node.Nodes.GetEnumerator(); } // Return this node yield return node; } // Is there a previous level ? else if (enumerators.Count != 0) { // Clean up IDisposable disposable = currentEnumerator as IDisposable; disposable?.Dispose(); // Previous level currentEnumerator = enumerators.Pop(); } // Then, we're done else yield break; } } finally { // Clean up the enumerators foreach (IDisposable disposable in enumerators.OfType<IDisposable>()) { disposable.Dispose(); } } }