Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I exit a foreach loop in C#?

Tags:

c#

foreach

People also ask

How do you exit a forEach?

There is no way to stop or break a forEach() loop other than by throwing an exception. If you need such behavior, the forEach() method is the wrong tool.

How do you end a foreach loop in C#?

Exit Foreach Loop Using break Keyword In C# Let's say you have a list of colors or an array of colors and you are looping through the list and now you have to exit the foreach loop, you will use the break keyword to exit the loop.

Does continue break out of foreach loop?

Continue is not the opposite of break , break stops the loop, continue stops the current iteration.

Can we use break in forEach C#?

Break statement can be used in the following scenarios: for loop (For loop & nested for loop and Parallel. for) foreach loop (foreach loop & nested foreach loop and Parallel.


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);

Just use the statement:

break;

Use the break keyword.


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;
   }
}