4

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

TheGeneral
  • 79,002
  • 9
  • 103
  • 141
Muppet
  • 5,767
  • 6
  • 29
  • 39

3 Answers3

5

You could use a goto, anonymous method, wrap it in a method, or C#7 you could use a local function

static void Main(string[] args)
{
   void localMethod()
   {
      foreach (var enemyUnit in nearbyEnemyUnits)
         foreach (var ownUnit in ownUnits)
            if (ownUnit.EngagedTargetTag == enemyUnit.tag)
               return;
   }

   localMethod();
}

Additional Resources

TheGeneral
  • 79,002
  • 9
  • 103
  • 141
3

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);
Paul Hebert
  • 296
  • 3
  • 8
  • Isn't LINQ considered to be a tad slower than a loop like above? I am calling this function many times per second, so it needs to be very performant. Is LINQ then still the bettter alternative in your opinion? – Muppet Dec 31 '18 at 00:38
  • According to an old article that I dug up a LINQ statement isn't any slower than a foreach loop. If you are concerned about speed you would have to use for loops. But LINQ is easier to read and readability helps when weeks/years from now you have to go back to this code and figure out what you did. https://stackoverflow.com/questions/3156059/is-a-linq-statement-faster-than-a-foreach-loop http://www.schnieds.com/2009/03/linq-vs-foreach-vs-for-loop-performance.html – Paul Hebert Dec 31 '18 at 02:16
1

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://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/goto

b.pell
  • 3,873
  • 2
  • 28
  • 39