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,
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.
Breaking Out of For Loops. To break out of a for loop, you can use the endloop, continue, resume, or return statement.
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
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 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With