c# - Infinite IEnumerable in a foreach loop -
After answering, I put the following C # code together for fun:
Public stable IEnumerable & lt; Integer & gt; Fibonacci (maximum max) {int m1 = 0; Int M2 = 1; Int r = 1; While (R & lt; = max) {yield returns r; R = M1 + M2; M1 = M2; M2 = R; }} In foreach (FibonacciTo (56) int i. Where (n = & gt; n & gt; = 24)) {Console.WriteLine (i); } The problem is that there is no need to pass the maximum parameter in the function. I still, if I do not use one, the code produces the right data , But then looks hanging because IEnumerable continues to work. How can I write it so that I can use it like this:
foreach (I int in Fibonacci). Where (n = & gt; n> = 24 & amp; amp; n & lt; = 56)) {Console.WriteLine (i); }
You must use a combination of SkipWhile and After this move .
foreach (I int in Fibonacci). SkipWhile (n = & gt; n & lt; 24). Take while (n = & gt; n & lt; = 56)) {Console.WriteLine (i); } They are able to eliminate the ends on a condition; Where the input ends (in your case, never), its input (appropriately filtering) ends.
Comments
Post a Comment