6

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.

The reason I'm asking is that I've been just watching some presentation about good programming principles and there was a thread about declarative vs. imperative code. What caught my attention was a way you can generate a pseudo-infinite set of data.

i3arnon
  • 113,022
  • 33
  • 324
  • 344
SOReader
  • 5,697
  • 5
  • 31
  • 53

1 Answers1

13

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<T> Iterate<T>(T seed, Func<T,T> 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)

i3arnon
  • 113,022
  • 33
  • 324
  • 344
  • I actually didn't want to write new extension method. – SOReader Nov 07 '14 at 14:03
  • 3
    @SOReader Then use MoreLINQ. – i3arnon Nov 07 '14 at 14:11
  • 2
    This should be marked as the answer here. It provides a clear answer (which is "no, there isn't") while also providing a very common alternative in the `MoreLinq` library as well as handcrafted code to achieve it without the library. – julealgon Nov 21 '18 at 15:08