Is it possible, in C#, to store execution commands in a List and carry out in a loop

Viewed 93

Lets say I have the following lines of code:

 callBacksToSend.Send(vaProxy, "a1", "b1");
 callBacksToSend.Send(vaProxy, "a2", "b2", c2);
 callBacksToSend.Send(vaProxy, "a3", "b3");
 callBacksToSend.Send(vaProxy, "a4", "b4");
.
.
.
 callBacksToSend.Send(vaProxy, "an", "bn", cn);

How can I store all the above in a LIST or array or Dictionary, and run in a loop? I need this because I want to run a check after each command is carried out.

2 Answers

You could use lambda expressions to do something like this

var actions = new List<Action>() {
   () => foo.Send(vaProxy, "a1", "b1"),
   () => foo.Send(vaProxy, "a2", "b2", c2)
   //....
};

foreach (var a in actions) {
    a();
    Console.WriteLine("did an action!");
}

Instead of having a list of delegates I suggest to use a list of arguments

var args = new[] { new[] { "a1", "b1" }, new[] { "a2, "b2" }, ... };
foreach(var arg in args)
    callbacks.Send(vaProxy, arg[0], arg[1]);

If the args may vary you can also extract some class for them:

class Arg
{
    string Item1;
    string Item2;
    int Item3;
    ...
}

Now create a list of those and loop them:

var args = new[] { new Arg { ... }, new Arg { ... }, ...};
foreach(var arg in args)
    callbacks.Send(vaProxy, arg);
Related