Infinite IEnumerable in a foreach loop

Answering this question , I compiled the following C # code just for fun:

public static IEnumerable<int> FibonacciTo(int max)
{     
    int m1 = 0;
    int m2 = 1;
    int r = 1;

    while (r <= max)
    {
       yield return r;

       r = m1 + m2;
       m1 = m2;
       m2 = r;
    }
}

foreach (int i in FibonacciTo(56).Where(n => n >= 24) )
{
   Console.WriteLine(i);
}

The problem is that I don't like passing parameter to a maxfunction. Right now, if I do not use one, the code will produce the correct data, but then it will be visible when IEnumerable continues to work. How can I write this so that I can just use it like this:

foreach (int i in Fibonacci().Where(n => n >= 24 && n <= 56) )
{
   Console.WriteLine(i);
}
+5
source share
2 answers

Instead, you need to use a combination of SkipWhileand TakeWhile.

foreach (int i in Fibonacci().SkipWhile(n => n < 24)
                             .TakeWhile(n => n <= 56))
{
   Console.WriteLine(i);
}

; Where ( ) , ( ).

+12

, , LINQ. , , LINQ , IEnumerable, .

-2

All Articles