How to end the foreach loop in C#?

In C#, you can use the break keyword to end a foreach loop. When the break keyword is encountered, the loop will immediately stop, and the program will execute the code after the foreach loop. Here is an example:

int[] numbers = { 1, 2, 3, 4, 5 };

foreach (int number in numbers)
{
    if (number == 3)
    {
        break; // 结束循环
    }
    Console.WriteLine(number);
}

Console.WriteLine("循环结束");

The output result is:

1
2
循环结束

In the example above, the loop was terminated using the break keyword when number was equal to 3.

bannerAds