If you are going to split this out, I would actually split the recursion part from the "what you do with each node" part. So something like this:
public static void ApplyRecursively<T>(this IEnumerable<T> source,
Action<T> action,
Func<T, IEnumerable<T>> childSelector)
{
// TODO: Validation
foreach (var item in source)
{
action(item);
childSelector(item).ApplyRecursively(action, childSelector);
}
}
Then you can call it as:
allNodes.ApplyRecursively(node => MessageBox.Show(node.ToString()),
node => node.Nodes);
This is assuming you're using a proper generic TreeView
/ TreeNode
class pair. If these are the ones from System.Windows.Forms
, you'll need to call Cast
as well.
allNodes.Cast<TreeNode>()
.ApplyRecursively(node => MessageBox.Show(node.ToString()),
node => node.Nodes.Cast<TreeNode>());