Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to break out of 2 loops without a flag variable in C#?

Tags:

syntax

c#

As a trivial example lets say I have the following grid and I am looking for a particular cells value. When found I no longer need to process the loops.

foreach(DataGridViewRow row in grid.Rows) {     foreach(DataGridViewCell cell in row.Cells)     {         if(cell.Value == myValue)         {             //Do Something useful             //break out of both foreach loops.         }     } } 

How is this done in C#. In Java I could use a label to name the outermost loop, and then break that loop, but I can't seem to find an equivelant in C#.

What is the tersest way of accomplishing this in c#? I know I can set a boolean flag, and check it in the outer loop to break out of that one as well, but it just seems too verbose.

Thanks,

like image 994
Matthew Vines Avatar asked Jun 11 '09 17:06

Matthew Vines


People also ask

Can you break from two loops?

In a nested loop, a break statement only stops the loop it is placed in. Therefore, if a break is placed in the inner loop, the outer loop still continues. However, if the break is placed in the outer loop, all of the looping stops.

How do you break out of a loop in a loop?

Breaking Out of For Loops. To break out of a for loop, you can use the endloop, continue, resume, or return statement.

How many loops does break break C?

The break statement is used inside loops or switch statement. The break statement breaks the loop one by one, i.e., in the case of nested loops, it breaks the inner loop first and then proceeds to outer loops.


1 Answers

1

foreach(DataGridViewRow row in grid.Rows)    foreach(DataGridView cell in row.Cells)       if (cell.Value == somevalue) {          // do stuff          goto End;       } End:    // more stuff 

2

void Loop(grid) {     foreach(row in grid.Rows)        foreach(cell in row.Cells)            if (something) {                // do stuff                   return;            } } 

3

var cell = (from row in grid.Rows.OfType<DataGridViewRow>()             from cell in row.Cells.OfType<DataGridViewCell>()             where cell.Value == somevalue             select cell    ).FirstOrDefault();  if (cell != null) {    // do stuff } 
like image 109
Jimmy Avatar answered Oct 07 '22 07:10

Jimmy