Is there a shorter/simpler version of the for loop to anything x times?
One can create an IEnumerable
of Int32:
Enumerable.Range(0, 10);
The ForEach extension method is also widely known (although not shipped with .NET). You could combine the two:
Enumerable.Range(0, 10).ForEach(index => ...);
So your example would become:
Enumerable.Range(0, 10).ForEach(_ => list.Add(GetRandomItem()));
foreach (var i in Enumerable.Range(0, N))
{
// do something
}
Well you can easily write your own extension method:
public static void Times(this int count, Action action)
{
for (int i = 0; i < count; i++)
{
action();
}
}
Then you can write:
10.Times(() => list.Add(GetRandomItem()));
I'm not sure I'd actually suggest that you do that, but it's an option. I don't believe there's anything like that in the framework, although you can use Enumerable.Range
or Enumerable.Repeat
to create a lazy sequence of an appropriate length, which can be useful in some situations.
As of C# 6, you can still access a static method conveniently without creating an extension method, using a using static
directive to import it. For example:
// Normally in a namespace, of course.
public class LoopUtilities
{
public static void Repeat(int count, Action action)
{
for (int i = 0; i < count; i++)
{
action();
}
}
}
Then when you want to use it:
using static LoopUtilities;
// Class declaration etc, then:
Repeat(5, () => Console.WriteLine("Hello."));