user3328730
user3328730

Reputation:

Action<> object as a parameter to function and using it

I have this function as a solution to traversing my treeview:

protected void PerformActionOnNodesRecursive(TreeViewNodeCollection nodes, Action<TreeViewNode> action)
{
    foreach (TreeViewNode node in nodes)
    {
        action(node);
        if (node.Nodes.Count > 0)
            PerformActionOnNodesRecursive(node.Nodes, action);
    }
}

But what I couldn't understand is how do I implement my action or the required action for each node.

Can any one please tell me how to use this action object and define a custom action?

Upvotes: 2

Views: 94

Answers (2)

Patrick Hofman
Patrick Hofman

Reputation: 157136

You an call the Action like this:

PerformActionOnNodesRecursive(node.Nodes, (node) => node.SomeProperty = "123");

Or:

PerformActionOnNodesRecursive(node.Nodes, (node) => 
    {
        // you can place multiple statements here.
    });

Or:

PerformActionOnNodesRecursive(node.Nodes, (node) => CallSomeOtherMethod(node));

Some useful information on lambda expression can be found on MSDN.

Upvotes: 4

Michael Mairegger
Michael Mairegger

Reputation: 7301

You can create your Action as follows:

PerformActionOnNodedRecursive(node, new Action(t => t.Text = "Test"));

Now every child node and the node itself will receive the Text "Test"

Upvotes: 0

Related Questions