Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an elegant way to repeat an action?

In C#, using .NET Framework 4, is there an elegant way to repeat the same action a determined number of times? For example, instead of:

int repeat = 10; for (int i = 0; i < repeat; i++) {     Console.WriteLine("Hello World.");     this.DoSomeStuff(); } 

I would like to write something like:

Action toRepeat = () => {     Console.WriteLine("Hello World.");     this.DoSomeStuff(); };  toRepeat.Repeat(10); 

or:

Enumerable.Repeat(10, () => {     Console.WriteLine("Hello World.");     this.DoSomeStuff(); }); 

I know I can create my own extension method for the first example, but isn't there an existent feature which makes it already possible to do this?

like image 725
Arseni Mourzenko Avatar asked Jun 20 '11 04:06

Arseni Mourzenko


People also ask

How to repeat a function in c sharp?

String Repeat ImplementationsPadLeft - string is repeated using empty string, PadLef() method and Replace() method. Replace - string is repeated using String constructor and Replace() method. Concat - string is repeated using Concat() method on Enumerable. Repeat()

What is enumerable repeat in C#?

Enumerable. Repeat method is part of System. Linq namespace. It returns a collection with repeated elements in C#. Firstly, set which element you want to repeat and how many times.

How do I print a string multiple times in C#?

Use string. Concat(Enumerable. Repeat(charToRepeat, 5)) to repeat the character "!" with specified number of times. Use StringBuilder builder = new StringBuilder(stringToRepeat.


1 Answers

Like this?

using System.Linq;  Enumerable.Range(0, 10).ForEach(arg => toRepeat()); 

This will execute your method 10 times.

[Edit]

I am so used to having ForEach extension method on Enumerable, that I forgot it is not part of FCL.

public static void ForEach<T>(this IEnumerable<T> source, Action<T> action) {     foreach (var item in source)         action(item); } 

Here is what you can do without ForEach extension method:

Enumerable.Range(0, 10).ToList().ForEach(arg => toRepeat()); 

[Edit]

I think that the most elegant solution is to implement reusable method:

public static void RepeatAction(int repeatCount, Action action) {     for (int i = 0; i < repeatCount; i++)         action(); } 

Usage:

RepeatAction(10, () => { Console.WriteLine("Hello World."); }); 
like image 120
Alex Aza Avatar answered Sep 24 '22 15:09

Alex Aza