Is there an elegant way to repeat an action?

后端 未结 9 1244
野的像风
野的像风 2020-12-16 08:56

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          


        
相关标签:
9条回答
  • 2020-12-16 09:55

    Most convenient I find is:

    Enumerable.Range(0, 10).Select(_ => action());
    
    0 讨论(0)
  • 2020-12-16 09:57

    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."); });
    
    0 讨论(0)
  • 2020-12-16 09:57

    Declare an extension:

    public static void Repeat(this Action action, int times){
        while (times-- > 0)
            action.Invoke();
    }
    

    You can use the extension method as:

            new Action(() =>
                       {
                           Console.WriteLine("Hello World.");
                           this.DoSomeStuff();
                       }).Repeat(10);
    
    0 讨论(0)
提交回复
热议问题