How to break out of a foreach loop in C#?
In C#, the break keyword can be used to exit a foreach loop. It can be used when there is a need to exit the loop based on a certain condition. For example:
foreach (var item in collection)
{
if (item == target)
{
break; // 跳出循环
}
}
It’s important to note that the “break” statement can only exit the current loop. If there are multiple nested loops, “break” will only exit the innermost loop. If you need to exit an outer loop, you can use the “goto” statement or replace a “foreach” loop with a “for” loop or “while” loop.