Is there an elegant way to repeat an action?
Like this?
using System.Linq;
Enumerable.Range(0, 10).ForEach(arg => toRepeat());
This will execute your method 10 times.
[Edit]
I am so used to having ForEach
extension method on Enumerable, that I forgot it is not part of FCL.
public static void ForEach<T>(this IEnumerable<T> source, Action<T> action)
{
foreach (var item in source)
action(item);
}
Here is what you can do without ForEach
extension method:
Enumerable.Range(0, 10).ToList().ForEach(arg => toRepeat());
[Edit]
I think that the most elegant solution is to implement reusable method:
public static void RepeatAction(int repeatCount, Action action)
{
for (int i = 0; i < repeatCount; i++)
action();
}
Usage:
RepeatAction(10, () => { Console.WriteLine("Hello World."); });
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 Where
, Select
, etc., but you do not get ForEach
.1
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.