In C#, using .NET Framework 4, is there an elegant way to repeat the same action a determined number of times? For example, instead of:
int repeat = 10;
for (int i = 0; i < repeat; i++)
Action toRepeat = () =>
Enumerable.Repeat(10, () =>
There is no built-in way to do this.
The reason is that C# as it is tries to enforce a divide between the functional and imperative sides of the language. C# only makes it easy to do functional programming when it is not going to produce side effects. Thus you get collection-manipulation methods like LINQ's
Select, etc., but you do not get
In a similar way, what you are trying to do here is find some functional way of expressing what is essentially an imperative action. Although C# gives you the tools to do this, it does not try to make it easy for you, as doing so makes your code unclear and non-idiomatic.
1 There is a
List<T>.ForEach, but not an
IEnumerable<T>.ForEach. I would say the existence of
List<T>.ForEach is a historical artifact stemming from the framework designers not having thought through these issues around the time of .NET 2.0; the need for a clear division only became apparent in 3.0.