tags:

views:

63

answers:

4

For example if i have to type something like that multiple time, is there any way to put this loop in the method with parameters like LoopMethod(Code lines, int count)

        for (int i = 0; i <= 1000; i++)
        {
            code line 1;
            code line 2;
            ...
            code line N;
        }

        for (int i = 0; i <= 1000; i++)
        {
            code line 1;
            code line 2;
            ...
            code line N;
        }

if result to have something like that.

LoopMethod{
            code line 1,
            code line 2,
            ...
            code line N,
            1000
}
+3  A: 

Here's a variant:

public static LoopMethod(int iterations, Action<int> body)
{
    for (int i = 0; i < iterations; i++)
        body(i);
}

You'd call it like this:

LoopMethod(100, i =>
{
    code line;
    code line;
});
Gabe
A: 

Well, you can do that with delegates rather easily:

public static void LoopMethod(Action loopCode, int count)
{
    for (int i = 0; i < count ; ++i) loopCode();
}

public static void Main()
{
    LoopMethod(() => {
        code line 1;
        code line 2;
        code line 3;
    }, 100);
}

You can alter that any way you like, even changing it to Action<int> which takes as a parameter the current loop counter. See @Gabe's answer for the Action<int> variant :)

Of course, I have to wonder why you want to reproduce such an obviously built-in construct like looping?

James Dunne
+2  A: 

A more generic form would be to first create an extension method:

public static class Extension
{
    public static void ForEach<T>(this IEnumerable<T> enumerable, Action<T> action)
    {
        foreach(var currentItem in enumerable)
        {
            action(currentItem);
        }
    }
}

Then using that you can do the following:

        Enumerable.Range(0, 1000).ForEach(i =>
                                              {
                                                  Console.WriteLine(i);
                                              });

Which would iterate from 0 to 999 (use 1001 as the second param for inclusive). The added benefit is that this then works on any enumerable type.

Joshua Rodgers
thanks! very cool way of doing this.
Greon
A: 

You could use lambda expression like this:

LoopMethod(() => {code line 1; code line 2;}, 100);

The method declaration would look something like

void LoopMethod (Action code, int count) {
     for (int i = 0; i < count; i++) {
         code();
     }
}

There may be odd syntactical error there ( I haven't tested it), but the approach should work.

Andrew Cooper