C# infinite iteration

后端 未结 1 1049
甜味超标
甜味超标 2021-01-18 18:59

Is there anything similar in C# to Java\'s Stream.iterate? The closest thing I could find was Enumerable.Range but it is much different.

Th

1条回答
  •  长情又很酷
    2021-01-18 19:16

    There isn't an exact equivalent in the .Net framework but there is one in the MoreLINQ library:

    foreach (var current in MoreEnumerable.Generate(5, n => n + 2).Take(10))
    {
        Console.WriteLine(current);
    }
    

    It's also very simple to recreate it using yield:

    public static IEnumerable Iterate(T seed, Func unaryOperator)
    {
        while (true)
        {
            yield return seed;
            seed = unaryOperator(seed);
        }
    }
    

    yield enables to create an infinite enumerator because:

    When a yield return statement is reached in the iterator method, expression is returned, and the current location in code is retained. Execution is restarted from that location the next time that the iterator function is called.

    From yield (C# Reference)

    0 讨论(0)
提交回复
热议问题