简体   繁体   中英

C# - repeat for loop without using goto

Recently, when developing a calculator program, I found myself using goto multiple times to restart a for loop. Example:

StartLoop:

for (int i = 0; i < length; i++)
{
    if (items[i] == condition)
    {
        //Do something
        goto StartLoop:
    }
}

I know that goto should be avoided but what other way would I have to restart the loop?

Just set the value of i :

int length = 9;
for (int i = 0; i < length; i++)
{
    Console.WriteLine(i);
    if (i == 7)
    {
        i = -1;
    }
}
0
1
2
3
4
5
6
7
0
1
2
3
4
5
6
7
0
1
2
3
4
5
...

As per a comment from /u/Tim Schmelter, it's probably going to be clearer to split the logic into multiple methods.

If you put the loop into a bool-returning method, you can then return a value which indicates whether the loop was terminated prematurely. There's a myriad ways to do that; here's one example:

void processItemsUntilComplete(int[] items)
{
    static bool condition(int item) => item == 42;

    while (!processItemsUntil(items, condition))
    {
        // Keep looping until processItems() returns true to indicate that it completed.
    }
}

/// <summary>Processes items until a certain condition occurs.</summary>
/// <returns>True if all the items were processed; false if the processing was interrupted because the condition was true.</returns>
bool processItemsUntil(int[] items, Predicate<int> condition)
{
    foreach (var item in items)
    {
        if (condition(item))
            return false;

        // Other processing.
    }

    return true;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM