foreach循环与条件 [英] foreach loop with conditions

查看:229
本文介绍了foreach循环与条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我能做到循环使用一个以上的情况是这样的:

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

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

}

有没有办法使用的foreach做到这一点:

Is there any way to do it using foreach:

foreach (var i in arr and while condition1 && condition2 && ... && conditionN) {
}

但是,如果没有使用突破;

我需要这一点是为了传递可枚举,我不想继续迭代,如果我的条件是不正确的。

I need this in order to pass on Enumerable and I don't want continue iterations if my condition is not true.

推荐答案

您可以使用<一个href="http://msdn.microsoft.com/en-us/library/system.linq.enumerable.takewhile.aspx">Enumerable.TakeWhile扩展方法:

foreach (var i in arr.TakeWhile(j => condition1 && ... && conditionN))
{
    // do something
}

这是大致相当于:

foreach (var j in arr)
{
    if (!(condition1 && ... && conditionN))
    {
        break;
    }
    var i = j;
    // do something
}

这篇关于foreach循环与条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆