foreach loop with conditions

后端 未结 1 859
温柔的废话
温柔的废话 2021-02-05 06:23

I can do loop with more then one condition like this:

for (int i = 0; condition1 && condition2 && ... && conditionN  ; i++) {

}
<         


        
1条回答
  •  旧时难觅i
    2021-02-05 06:44

    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 讨论(0)
提交回复
热议问题