繁体   English   中英

C# - 带有 if 语句的 Foreach 循环

[英]C# - Foreach loop with if statement

如果“if”语句为真,我该怎么做才能跳过 foreach 循环下面的代码并继续执行程序的其余部分

void()
{
    foreach()
    {
        if()
        {

        }
    }

    //code I want to skip if "if" statement is true

}

没有办法直接做你想做的事(没有“goto”标签 - 放弃这个想法!),但你可以使用“break”关键字,并设置一个你可以稍后引用的变量。

void()
{
    var testWasTrue = false;
    foreach()
    {
        if()
        {
            testWasTrue = true;
            break;  // break out of the "foreach"
        }
    }

    if( !testWasTrue ) {
        //code I want to skip if "if" statement is true
    }

}

我知道这已经得到了回答,但我想我会投入 2 美分,因为没有人考虑将支票抽象为单独的方法:

void()
{
    if (ShouldDoStuff(myCollection))
        DoStuff(myCollection);
    else
        DoOtherStuff(myCollection);
}

private bool ShouldDoStuff(collection)
{
    foreach()
    {
        if ()
            return true;
    }
    return false;
}

这在更高级别提供了一个更清晰的代码来处理您的算法并消除所有讨论的混乱。 它干净地将检查和执行操作的void()中的任务分开,读者可以立即确切地知道程序流是什么,而无需通过隐藏的布尔值或中断逻辑来辨别他们正在做什么。 没有一种方法具有超过 1 个职责或任务。

是的,发布者可能想在他们的 foreach 中做其他工作,但这是一个完全不同的讨论,而不是他们的问题中描述的内容。 如果您只想检查给定的集合(或对象)是否满足特定条件,则可以将该检查移至单独的方法。 甚至为所有三个组件的自动化单元测试敞开大门。

即使DoStuffDoOtherStuff没有抽象为它们自己的方法,它也提供了更好的可读性和逻辑流程。

'break' 关键字将跳出循环。

foreach (someClass a in someArray) 
{
  if(a.someProperty) // bool property 
  {
    //Stuff to do if that condition is true
    doSomethingElse();
    //Calling the break keyword will stop the loop and jump immediately outside of it
    break;
  }
  //Other code to run for each iteration of the loop
}

//Here is where execution will pick up either after break is called or after the loop finishes
void()
{
     bool process = true;
     foreach()
     {
          if()
          {
              process = false;
              break;
          }
     }

     if (process)
     {
       //code I want to skip if "if" statement is true
     }

}

正如我在评论中提到的,您可以通过额外的 bool 变量来做到这一点。

void()
    {
        bool positiveResult; // by default it gets false value
        foreach()
        {
            if()
            {
                positiveResult = true;
                // you may use "break" to skip the loop
                break;
            }
        }

        if( !positiveResult  ) 
         {
            //code I want to skip if "if" statement is true
         }

    }
void() 
{ 
    bool skip = false;
    foreach() 
    { 
        if() 
        { 
           skip = true;
        } 
    } 

    if(!skip)
    {
        //code I want to skip if "if" statement is true 
    }
} 

我知道布尔标志的唯一方式。

void()
{
  bool x = false;
  foreach()
  {
    if()
    {
      x = true;
      break;
    }
  }
  if(!x)
  {
    //Code to skip if "if" statement is true.
  }
}

不是超级优雅,但很容易。 编辑:击败 12 秒 :)

如果您正在迭代的集合包含 IEnumerable 接口,您可以将 Any() 与 Lambda 一起使用!

int[] myArray = { 1, 2, 3 };

                if( myArray.Any((a) => a == 1) )
                {
                    return;
                }

读取:如果我的数组包含任何值 a,其中 a 等于 1,则返回此函数。

另外,如果你想让它更难阅读,你可以省略花括号/方括号。

if( myArray.Any((a) => a == 1) )
     return;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM