<p>Every time I need to do something <em>N</em> times inside an algorithm using C# I write this code</p>

<pre><code>for (int i = 0; i &lt; N; i++)
{
    ...
}
</code></pre>

<p>Studying Ruby I have learned about method <em>times()</em> which can be used with the same semantics like this</p>

<pre><code>N.times do
    ...
end
</code></pre>

<p>Code fragment in C# looks more complex and we should declare useless variable <em>i</em>.</p>

<p>I tried to write extension method which returns <em>IEnumerable</em>, but I am not satisfied with the result because again I have to declare a cycle variable <em>i</em>.</p>

<pre><code>public static class IntExtender
{
    public static IEnumerable Times(this int times)
    {
        for (int i = 0; i &lt; times; i++)
            yield return true;
    }
}

...

foreach (var i in 5.Times())
{
    ...
}
</code></pre>

<p>Is it possible using some new C# 3.0 language features to make <em>N</em> times cycle more elegant?</p>

It is indeed possible with C# 3.0:
```
```
public interface ILoopIterator
{
    void Do(Action action);
    void Do(Action<int> action);
}

private class LoopIterator : ILoopIterator
{
    private readonly int _start, _end;

    public LoopIterator(int count)
    {
        _start = 0;
        _end = count - 1;
    }

    public LoopIterator(int start, int end)
    {
        _start = start;
        _end = end;
    }  

    public void Do(Action action)
    {
        for (int i = _start; i <= _end; i++)
        {
            action();
        }
    }

    public void Do(Action<int> action)
    {
        for (int i = _start; i <= _end; i++)
        {
            action(i);
        }
    }
}

public static ILoopIterator Times(this int count)
{
    return new LoopIterator(count);
}
```
```
Usage:
```
```
int sum = 0;
5.Times().Do( i => 
    sum += i
);
```
```
Shamelessly stolen from
http://grabbagoft.blogspot.com/2007/10/ruby-style-loops-in-c-30.html