Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

if/else iterating over same variable in two different for loops

Is there a better (more concise) way of iterating over the same collections objects in an if/else condition than the following:

bool condition = DetermineConditionValue();

if(condition)
{
    foreach(var v in variables)
    {
        PerformAction(v);
    }
else
{
    foreach(var v in variables)
    {
        PerformAnotherAction(v);
    }
}

Is there a better way to avoid writing the loop twice?

like image 331
A.Fakhry Avatar asked Jan 01 '23 06:01

A.Fakhry


1 Answers

You could use Action<T>

Action<YourParameterTypeHere> actionToDo = DetermineConditionValue()
      ? PerformAction 
      : PerformAnotherAction;

foreach(var v in variables)
{
    actionToDo(v);
}
like image 197
Igor Avatar answered Jan 05 '23 15:01

Igor