开发者

foreach loop with conditions

开发者 https://www.devze.com 2023-03-27 18:24 出处:网络
I can do loop with more then one condition like this: for (int i = 0; condition1 && condition2 && ... && conditionN; i++) {

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

精彩评论

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

关注公众号