Possible Duplicate:
Breaking out of a nested loop
I got somthing like (to simplify)
foreach (...)
{
foreach (...)
{
//Some code
if (statement)
{
break;
}
}
}
The thing is that I want my statement to leave for the double-foreach loop ! I'm thinking about a sort of "break flag" as a boolean but is there any way to avoid that ?
You could avoid the nested loop entirely by using Linq and SelectMany
.
Instead of:
foreach(var value in someValues)
{
foreach(var subValue in value.SubValues)
{
// ...
break;
}
}
Your code would become:
foreach(var subValue in someValues.SelectMany(v => v.SubValues))
{
// ...
break;
}
If you need some logic to select whether or not you loop over SubValues
, throw that logic in an additional Where
clause.
Instead of
foreach(var value in someValues)
{
if(value.IsMumsHairGreenToday)
{
foreach(var subValue in value.SubValues)
{
// ...
break;
}
}
}
You can write:
var subValues = someValues
.Where(v => v.IsMumsHairGreenToday)
.SelectMany(v => v.SubValues)
;
foreach(var subValue in subValues)
{
// ...
break;
}
You may use goto.
Sure, you should check goto.
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