Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

loops

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

like image 417
Muppet Avatar asked Jan 01 '23 11:01

Muppet


1 Answers

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

  • goto (C# Reference)

  • Anonymous Methods (C# Programming Guide)

  • Local functions (C# Programming Guide)

like image 101
TheGeneral Avatar answered Jan 29 '23 11:01

TheGeneral