开发者

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜