How can I efficiently break out of a double loop in C#?

Viewed 120

Here is what I currently use to break out of a double loop and proceed with DoStuff():

foreach (var enemyUnit in nearbyEnemyUnits) {
    var skip = false;
    foreach (var ownUnit in ownUnits) {
        if (ownUnit.EngagedTargetTag == enemyUnit.tag) {
            skip = true;
            break;
        }
    }

    if (skip) continue;

    DoStuff(enemyUnit);
}

The whole "defining a temporary boolean variable to check for a skip" seems very hacky to me. In a language like Go I can use labels to break out of loops, or even make the inner loop part of a clojure. What is the best way to do this in C#?

I've been doing it like the above example for the longest time and feel like there must be a better way - almost ashamed to ask at this point.

Thank you

3 Answers

Why use a goto when you can just use linq

foreach (var enemyUnit in nearbyEnemyUnits.Where(e=>ownUnits.Any(e1=>e1.EngagedTargetTag == e.Tag) == false))
                DoStuff(enemyUnit);

I couldn't tell you the last time I used a goto, but you can in C#. Here's an example (attribution link at the end):

public class GotoTest1
{
    static void Main()
    {
        int x = 200, y = 4;
        int count = 0;
        string[,] array = new string[x, y];

        // Initialize the array:
        for (int i = 0; i < x; i++)

            for (int j = 0; j < y; j++)
                array[i, j] = (++count).ToString();

        // Read input:
        Console.Write("Enter the number to search for: ");

        // Input a string:
        string myNumber = Console.ReadLine();

        // Search:
        for (int i = 0; i < x; i++)
        {
            for (int j = 0; j < y; j++)
            {
                if (array[i, j].Equals(myNumber))
                {
                    goto Found;
                }
            }
        }

        Console.WriteLine("The number {0} was not found.", myNumber);
        goto Finish;

    Found:
        Console.WriteLine("The number {0} is found.", myNumber);

    Finish:
        Console.WriteLine("End of search.");


        // Keep the console open in debug mode.
        Console.WriteLine("Press any key to exit.");
        Console.ReadKey();
    }
}

https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/goto

Related