简体   繁体   English

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

[英]C# - Foreach loop with if statement

How can I go about doing this so if the "if" statement is true, to skip the code below the foreach loop and to go on with the rest of the program如果“if”语句为真,我该怎么做才能跳过 foreach 循环下面的代码并继续执行程序的其余部分

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

        }
    }

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

}

There's no way to directly do what you want (without "goto" labels -- perish the thought!), but you can use the "break" keyword, and set a variable you can refer to later.没有办法直接做你想做的事(没有“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
    }

}

I know this was already answered, but I figured I'd throw in my 2 cents since nobody considered abstracting the check to a separate method:我知道这已经得到了回答,但我想我会投入 2 美分,因为没有人考虑将支票抽象为单独的方法:

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

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

This provides a much cleaner code at the higher level for dealing with your algorithms and removes all the clutter discussed about.这在更高级别提供了一个更清晰的代码来处理您的算法并消除所有讨论的混乱。 It cleanly separates the tasks in void() of checking and performing the actions and readers instantly know exactly what the program flow is without having to discern what they're doing with a boolean or break logic lurking about.它干净地将检查和执行操作的void()中的任务分开,读者可以立即确切地知道程序流是什么,而无需通过隐藏的布尔值或中断逻辑来辨别他们正在做什么。 No single method has more than 1 responsibility or task.没有一种方法具有超过 1 个职责或任务。

Yeah, it's possible the poster wants to do other work in their foreach, but that's an entirely different discussion and not what was described in their question.是的,发布者可能想在他们的 foreach 中做其他工作,但这是一个完全不同的讨论,而不是他们的问题中描述的内容。 If you simply want to check if the given collection (or object) satisfies a certain condition, that check can be moved to a separate method.如果您只想检查给定的集合(或对象)是否满足特定条件,则可以将该检查移至单独的方法。 Even leaves the door open for automated unit tests for all three components.甚至为所有三个组件的自动化单元测试敞开大门。

Even if DoStuff and DoOtherStuff are not abstracted to their own methods, it provides nicer readability and logical flow.即使DoStuffDoOtherStuff没有抽象为它们自己的方法,它也提供了更好的可读性和逻辑流程。

The 'break' keyword will break out of the loop. '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
     }

}

As was mentioned in my comment you may do this through extra bool variable.正如我在评论中提到的,您可以通过额外的 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 
    }
} 

Only way I know how is a bool flag.我知道布尔标志的唯一方式。

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

Not super elegant, but easy.不是超级优雅,但很容易。 Edit: beat by 12 secs :)编辑:击败 12 秒 :)

If the collection you are iterating through contains The IEnumerable Interface, You could use Any() with a Lambda!如果您正在迭代的集合包含 IEnumerable 接口,您可以将 Any() 与 Lambda 一起使用!

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

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

It is read: if my array contains any value a where a is equal to 1, then return out of this function.读取:如果我的数组包含任何值 a,其中 a 等于 1,则返回此函数。

Plus if you want to make it harder to read, you can omit the curly braces/brackets.另外,如果你想让它更难阅读,你可以省略花括号/方括号。

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

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

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