Usually we do something like a for or while loop with a counter:
for (int i = 0; i < 10; i++)
{
list.Add(GetRandomItem());
}
but sometimes you mix up with boundaries. You could use a while loop instead, but if you make a mistake this loop is infinite…
In Perl for example I would use the more obvious
for(1..10){
list->add(getRandomItem());
}
Is there something like doitXtimes(10){...}?
Well you can easily write your own extension method:
Then you can write:
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.RangeorEnumerable.Repeatto 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 staticdirective to import it. For example:Then when you want to use it: