代码之家  ›  专栏  ›  技术社区  ›  Muppet

如何有效地打破C#中的双循环?[副本]

  •  4
  • Muppet  · 技术社区  · 6 年前

    下面是我当前用来打破双循环并继续使用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);
    }
    

    整个“定义一个临时布尔变量来检查跳过”对我来说似乎很老套。在像Go这样的语言中,我可以使用标签来打破循环,甚至使内部循环成为clojure的一部分。在C#中,最好的方法是什么?

    我已经像上面的例子那样做了很长时间了,我觉得一定有更好的方法——在这一点上我几乎不好意思问。

    非常感谢。

    3 回复  |  直到 6 年前
        1
  •  5
  •   TheGeneral    6 年前

    您可以使用goto、匿名方法,将其包装在方法中,或者使用C#7本地函数

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

    额外资源

        2
  •  3
  •   Paul Hebert    6 年前

    foreach (var enemyUnit in nearbyEnemyUnits.Where(e=>ownUnits.Any(e1=>e1.EngagedTargetTag == e.Tag) == false))
                    DoStuff(enemyUnit);
    
        3
  •  1
  •   b.pell    6 年前

    我不能告诉你我最后一次使用goto是什么时候,但你可以用C。下面是一个示例(末尾的属性链接):

    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