Home >Backend Development >C++ >How Can I Efficiently Exit Nested Loops in C#?

How Can I Efficiently Exit Nested Loops in C#?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2025-01-17 04:11:09514browse

How Can I Efficiently Exit Nested Loops in C#?

Effective exit method of C# nested loop

When dealing with nested loops, it is often necessary to exit all loops at the same time in advance. Several efficient techniques can be used for this purpose.

Goto statement (not recommended)

One way, although not advisable, is to use a goto statement:

<code class="language-c#">for (int i = 0; i < 10; i++)
{
    for (int j = 0; j < 10; j++)
    {
        if (/* 退出条件 */)
        {
            goto ExitLoops;
        }
    }
}
ExitLoops:;</code>

This approach is generally not recommended as it is difficult to read and error-prone.

Anonymous method

A more flexible approach is to encapsulate the nested loop in an anonymous method and exit using the return statement:

<code class="language-c#">Action work = delegate
{
    for (int x = 0; x < 10; x++)
    {
        for (int y = 0; y < 10; y++)
        {
            if (/* 退出条件 */)
            {
                return;
            }
        }
    }
};
work();</code>

In this case, the return statement in the anonymous method causes both nested loops to exit immediately.

Local functions (C# 7 and above)

Local functions introduced starting in C# 7 provide a more elegant solution:

<code class="language-c#">void Work()
{
    for (int x = 0; x < 10; x++)
    {
        for (int y = 0; y < 10; y++)
        {
            if (/* 退出条件 */)
            {
                return;
            }
        }
    }
}</code>

Local functions allow you to declare a method within another method, allowing you to use return statements to exit both loops while keeping your code structure clear.

The above is the detailed content of How Can I Efficiently Exit Nested Loops in C#?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn