4

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?

6
  • Use pointer to function
    – J. Smith
    Feb 21, 2019 at 21:48
  • 2
    I think this question will end up flagged as attracting too many opinions, rather than an actual answer. 'Better' is inherently subjective, and depends on what you want to do. The way you're currently doing it is probably better performance-wise than alternatives, though.
    – Phil M
    Feb 21, 2019 at 21:49
  • 2
    Well, you could put the if statement inside your foreach loop, but really I wouldn't get too concerned. As long as the code seems logical when you read it.
    – Ben
    Feb 21, 2019 at 21:51
  • By better I mean more concise way without having to sacrifice performance.
    – A.Fakhry
    Feb 21, 2019 at 21:51
  • 2
    On what kind of rotten potato do you want to run your code that you worry about performance differences when having the if inside the loop? Two words: Branch prediction. Okay, two more words: Speculative execution. Also, you would need to put the performance cost of if in relation to the performance cost of executing Perform(Another)Action, which probably alone makes the whole performance cost of if inside the loop insignificant...
    – user2819245
    Feb 21, 2019 at 22:30

1 Answer 1

9

You could use Action<T>

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

foreach(var v in variables)
{
    actionToDo(v);
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.