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){...}
?
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).
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."));
foreach (var i in Enumerable.Range(0, N)) { // do something }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With