Search code examples
c#recursiontreeviewanonymous-methods

Recursion and anonymous method in C#


Good day. I have method for recursive traverse TreeNode in TreeView:

public void ShowTree(TreeView tree)
{
    foreach (TreeNode node in tree.Nodes)
    {
        ShowNode(node);
    }
}

private void ShowNode(TreeNode node)
{
    MessageBox.Show(node.ToString());
    foreach (TreeNode child in node.Nodes)
    {
        ShowNode(child);
    }
}

But I must have excess method "ShowNode", that is not used anywhere else. How to make this method of anonymous and to merge these two methods?


Solution

  • 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>());