Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
162 views
in Technique[技术] by (71.8m points)

c# - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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."); });

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...