How to stop(break) "for" loop in c#?

I need to stop "for" cycle before it ends by itself. I have one "for" cycle in other. Here is my code(a simple example):

for (int i = 0; i < 100; i++)
        {
            for (int j = 0; j < 10; j++)
            {
                if (i == 5)
                {
                    //stop "for" cycle
                }
            }
        }

I want to stop the "for" cycle which is inside without stopping outside one. Which command should I use to manage that?

Answers


For just one layer of loop, you can use break.

for (int i = 0; i < 100; i++)
{
    for (int j = 0; j < 10; j++)
    {
        if (i == 5)
        {
            break; // <== Exits the 'j' loop, returns control
                   //     to the 'i' loop which continues
        }
    }
}

For nested loops, you may want to use a variable (for instance, a bool) that you set to a break condition. Looking at this page, I don't think C# has directed breaks as some other languages do.

bool keepGoing = true;
for (int i = 0; keepGoing && i < 100; i++)
{
    for (int j = 0; keepGoing && j < 10; j++)
    {
        if (i == 5)
        {
            keepGoing = false; // Stops both
        }
    }
}

    for (int i = 0; i < 100; i++)
    {
        for (int j = 0; j < 10; j++)
        {
            if (i == 5)
            {
                break;
            }
        }
    }

You can use break statements (which exit the innermost loop), or even a break to a label. Personally I don't like the latter as it means you need to maintain that label which makes code hard to read.

If you need to exit right out of an elaborate nested for loop structure then encode the whole thing in a function and use return. You can then even return a value.


You want to break two loops with a single command? Use a goto.

for (int i = 0; i < 100; i++)
{
    for (int j = 0; j < 100; j++)
    {
        if (i == 10 && j == 50)
            goto Exit;
    }

    continue;

Exit:
    break;
}

Other has already posted how to break just the inner loop.


Need Your Help

Convert MySQL date and time to datetime

mysql

I have a table which has 4 columns. Date login, date logout, time login, time logout.