How do I exit a foreach loop in C#?

后端 未结 5 1854
温柔的废话
温柔的废话 2020-12-09 14:36
foreach (var name in parent.names)
{
    if name.lastname == null)
    {
        Violated = true;
        this.message = \"lastname reqd\";
    }

    if (!Violated)         


        
相关标签:
5条回答
  • 2020-12-09 14:48

    Use the break keyword.

    0 讨论(0)
  • 2020-12-09 14:54

    During testing I found that foreach loop after break go to the loop beging and not out of the loop. So I changed foreach into for and break in this case work correctly- after break program flow goes out of the loop.

    0 讨论(0)
  • 2020-12-09 15:04

    Look at this code, it can help you to get out of the loop fast!

    foreach (var name in parent.names)
    {
       if (name.lastname == null)
       {
          Violated = true;
          this.message = "lastname reqd";
          break;
       }
       else if (name.firstname == null)
       {
          Violated = true;
          this.message = "firstname reqd";
          break;
       }
    }
    
    0 讨论(0)
  • 2020-12-09 15:07

    Use break.


    Unrelated to your question, I see in your code the line:

    Violated = !(name.firstname == null) ? false : true;
    

    In this line, you take a boolean value (name.firstname == null). Then, you apply the ! operator to it. Then, if the value is true, you set Violated to false; otherwise to true. So basically, Violated is set to the same value as the original expression (name.firstname == null). Why not use that, as in:

    Violated = (name.firstname == null);
    
    0 讨论(0)
  • 2020-12-09 15:11

    Just use the statement:

    break;
    
    0 讨论(0)
提交回复
热议问题