Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - Foreach loop with if statement

How can I go about doing this so if the "if" statement is true, to skip the code below the foreach loop and to go on with the rest of the program

void()
{
    foreach()
    {
        if()
        {

        }
    }

    //code I want to skip if "if" statement is true

}
like image 895
user1455112 Avatar asked Jun 19 '12 23:06

user1455112


3 Answers

There's no way to directly do what you want (without "goto" labels -- perish the thought!), but you can use the "break" keyword, and set a variable you can refer to later.

void()
{
    var testWasTrue = false;
    foreach()
    {
        if()
        {
            testWasTrue = true;
            break;  // break out of the "foreach"
        }
    }

    if( !testWasTrue ) {
        //code I want to skip if "if" statement is true
    }

}
like image 145
Ethan Brown Avatar answered Nov 02 '22 23:11

Ethan Brown


I know this was already answered, but I figured I'd throw in my 2 cents since nobody considered abstracting the check to a separate method:

void()
{
    if (ShouldDoStuff(myCollection))
        DoStuff(myCollection);
    else
        DoOtherStuff(myCollection);
}

private bool ShouldDoStuff(collection)
{
    foreach()
    {
        if ()
            return true;
    }
    return false;
}

This provides a much cleaner code at the higher level for dealing with your algorithms and removes all the clutter discussed about. It cleanly separates the tasks in void() of checking and performing the actions and readers instantly know exactly what the program flow is without having to discern what they're doing with a boolean or break logic lurking about. No single method has more than 1 responsibility or task.

Yeah, it's possible the poster wants to do other work in their foreach, but that's an entirely different discussion and not what was described in their question. If you simply want to check if the given collection (or object) satisfies a certain condition, that check can be moved to a separate method. Even leaves the door open for automated unit tests for all three components.

Even if DoStuff and DoOtherStuff are not abstracted to their own methods, it provides nicer readability and logical flow.

like image 38
Chris Sinclair Avatar answered Nov 03 '22 00:11

Chris Sinclair


void()
{
     bool process = true;
     foreach()
     {
          if()
          {
              process = false;
              break;
          }
     }

     if (process)
     {
       //code I want to skip if "if" statement is true
     }

}
like image 26
Urik Avatar answered Nov 03 '22 00:11

Urik