C# - Foreach loop with if statement

42,398

Solution 1

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
    }

}

Solution 2

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.

Solution 3

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

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

}

Solution 4

As was mentioned in my comment you may do this through extra bool variable.

void()
    {
        bool positiveResult; // by default it gets false value
        foreach()
        {
            if()
            {
                positiveResult = true;
                // you may use "break" to skip the loop
                break;
            }
        }

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

    }

Solution 5

The 'break' keyword will break out of the loop.

foreach (someClass a in someArray) 
{
  if(a.someProperty) // bool property 
  {
    //Stuff to do if that condition is true
    doSomethingElse();
    //Calling the break keyword will stop the loop and jump immediately outside of it
    break;
  }
  //Other code to run for each iteration of the loop
}

//Here is where execution will pick up either after break is called or after the loop finishes
Share:
42,398
user1455112
Author by

user1455112

Updated on February 17, 2020

Comments

  • user1455112
    user1455112 about 4 years

    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
    
    }
    
  • dodexahedron
    dodexahedron almost 12 years
    Don't bother with the boolean. Do the work and then break/return. If it's a significant block of code, it's easily arguable that it should be a function anyway. See my example below.
  • dodexahedron
    dodexahedron almost 12 years
    No need to iterate through the entire collection. Break or return as soon as possible. Also, nix the boolean. No need for that at all.
  • McAden
    McAden almost 12 years
    Except this is quite different from your answer.
  • Jon
    Jon almost 12 years
    The break is irrelevant since we don't know his logic. There could be code inside the loop that needs to be performed for all items.
  • dodexahedron
    dodexahedron almost 12 years
    Not the way his question is written. He says if the statement is true, "skip" to the code below. The break is necessary. The boolean, however, is not, and is just a waste of cycles and memory.
  • Ethan Brown
    Ethan Brown almost 12 years
    The boolean is necessary; if you carefully read the OPs question, you'll see that he wants to break out of the loop for a given condition, THEN skip over some additional code if the condition was true. Short of using the dreaded goto label, there's no way to do that without storing the condition as a boolean.
  • UnskilledBuild
    UnskilledBuild over 4 years
    As a side note, you can do this with any IEnumerable. So this could be a List, Array, LinkedList, Queue, Stack, Dictionary, etc. Also, you may have to import System.Linq.