Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net

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

like image 275
mbx Avatar asked Oct 14 '10 11:10

mbx


People also ask

Which for loop is most efficient?

If n is the size of input(positive), which function is most efficient(if the task to be performed is not an issue)? Explanation: The time complexity of first for loop is O(n). The time complexity of second for loop is O(n/2), equivalent to O(n) in asymptotic analysis. The time complexity of third for loop is O(logn).


2 Answers

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.")); 
like image 150
Jon Skeet Avatar answered Sep 18 '22 18:09

Jon Skeet


foreach (var i in Enumerable.Range(0, N)) {     // do something } 
like image 35
Grozz Avatar answered Sep 20 '22 18:09

Grozz