foreach loop with conditions
I can do loop with more then one condition like this:
for (int i = 0; condition1 && condition2 && ... && conditionN ; i++) {
}
Is there any way to do it using foreach:
foreach (var i in arr and while condition1 && condition2 && ... && conditionN) {
}
But without using b开发者_如何转开发reak;
?
I need this in order to pass on Enumerable and I don't want continue iterations if my condition is not true.
You can use the Enumerable.TakeWhile Extension Method:
foreach (var i in arr.TakeWhile(j => condition1 && ... && conditionN))
{
// do something
}
This is roughly equivalent to:
foreach (var j in arr)
{
if (!(condition1 && ... && conditionN))
{
break;
}
var i = j;
// do something
}
精彩评论