foreach中的当前和以前的值比较

时间:2013-06-27 06:15:05

标签: c# if-statement

任何解决方案都受到赞赏,与此方法无关。

foreach(var x in xs){
    var y = getValuesfromX(x);

    foreach(var yvalue in y){

        //Here I want if(yvalue is LESS than 100 and if (yvalue - previousyvalue) not   GEATER than 30){

       // perform action

        //else, quit looping xs am not interested anymore after the difference reached 30

1 个答案:

答案 0 :(得分:2)

您可以使用Zip运算符执行某些方法,但除此之外,将下一个值保留为先前值或 limit 可能最简单 - 作为变量:< / p>

foreach (var x in xs)
{
    var ys = GetValuesForX(x);
    int limit = int.MaxValue; // Any value is fine to start with.
    foreach (var y in ys)
    {
        if (y > limit)
        {
            break;
        }
        if (y < 100)
        {
            // Take some action 
        }
        limit = y + 30;
    }
}

请注意,如果y可能是int.MaxValue - 30,则会导致问题。