Search code examples
c#funcenumerable

Is there any way to repeat a Func<T, T> with Enumerable.Repeat method in C#?


I wrote a function that accepts (Func & int N) and repeats the Func N times and returns a result.

public IEnumerable<T> MyFunction(Func<T, T> function, int iteration)
{

}

Is there any way to repeat a function using Enumerable.Repeat?

public IEnumerable<T> MyFunction(Func<T, T> function, int iteration)
{
    yield return Enumerable.Repeat<T>(function.Invoke(), iteration);
}

I tried to run the code above, but the function runs once.


Solution

  • There is a way, although I'm not sure what it proves.

    static public IEnumerable<T> MyFunction<T>(Func<T> function, int iteration)
    {
        return Enumerable.Repeat(function, iteration).Select( x => x() );
    }
    
    public static void Main()
    {
        int n = 0;
    
        foreach (var i in MyFunction(() => n++, 10)) Console.WriteLine(i);
    }
    

    For some reason though it is more common to see people do it this way:

        return Enumerable.Range(0, iteration).Select( x => function() );
    

    I see the latter construct on Stackoverflow all the time.

    Output:

    0
    1
    2
    3
    4
    5
    6
    7
    8
    9