Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 561
Saleh Bagheri Avatar asked Oct 20 '25 15:10

Saleh Bagheri


1 Answers

Why not simply call the method in a loop:

for(int i = 0; i < iteration; i++)
    yield return function(myTInstance);

or in a Linq-statement:

return Enumerable.Range(0, iteration).Select(x => function(MyTInstance));
like image 167
MakePeaceGreatAgain Avatar answered Oct 23 '25 04:10

MakePeaceGreatAgain



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!