Is there a shorter/simpler version of the for loop to anything x times?

Viewed 68699

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){...}?

7 Answers
while (i-- > 0) {

}

You mentioned that while loop is dangerous as it may be infinite - the above form is pretty simple and will never be infinite. At least TOTALLY infinite :)

It's convenient and short (shorter than any of the other answers) and will run exactly i times (because postfix decrement returns value before decrementation).

There's still one way missing:

List<T> list = System.Linq.Enumerable.Range(0, 10).Select(_ => GetRandomItem()).ToList();

Where T is the type returned by GetRandomItem()

Related