Want to be able to write code like “5.Times” but you can’t use a language like Ruby? You can do this in C# with some extension method magic.
public static void Times(this int numberOfTimes, Action action)
{
for (var number = 0; number < numberOfTimes; number++)
{
action();
}
}
Now you can write code like:
5.Times(() => Console.WriteLine("Hello"));
Sometimes however you want to know the index of the invocation of the lambda. This can be done with:
public static void Times(this int numberOfTimes, Action<int> action)
{
for (var number = 0; number < numberOfTimes; number++)
{
action(number);
}
}
This allows:
3.Times(count => Console.WriteLine(count));
These are nifty for invoking some kind of logic a specified number of times. But what if your action returns a result you’d like to collect? Try:
public static IEnumerable<TResult> Times<TResult>(this int numberOfTimes, Func<int, TResult> func)
{
for (var number = 0; number < numberOfTimes; number++)
{
yield return func(number);
}
}
Rather than return void this returns an IEnumerable<T> that you can then use like so:
var result = 4.Times(count => count * count);
This code can be found in Avernus, but in most cases it’s probably more effective to copy it directly into your own project.