I have a TreeView Control with set of nodes and child nodes. For example:
ROOT has A,B,C.
A has a1, a2, a3 and then
I know this thread is quite old and my method doesn't exactly reduce the amount of recursion and it may be slightly slower but it makes my code a bit cleaner.
I use an extension method for IEnumarable<> to flatten any tree (not just TreeView nodes):
public static IEnumerable Flatten(
this IEnumerable rootNodes,
Func> childrenFunction)
{
return rootNodes.SelectMany(
child => new[] { child }
.Concat((childrenFunction(child) ?? Enumerable.Empty())
.Flatten(childrenFunction)));
}
I then use this method to get all the nodes of the tree:
IEnumerable allNodes = treeView1.Nodes.Cast()
.Flatten(n => n.Nodes.Cast());