Welcome to Honest Illusion Sign in | Join | Help

More Fun with C# Interators : A Counting Iterator

Michael Herman recently discovered a typo in the MSDN docs:   "IEnumberable: the integer version of IEnumerable? :-) "

 

This reminded me of a method that I've been planning on presenting here:  A simple Counting iterator.  Basically, it appears to be a collection filled with a sequences of numbers.  For example, the following code will print the number from 20 to 41 stepping by three:

foreach(int i in Iter.Count(20,41, 3))
     WL(i.ToString());

 

It's also good to create an actual collection pre-filled with sequence of numbers:

List<int> ll = new List<int>(Iter.Count(5));

The code follows:

static class Iter
{
    static public IEnumerable<int> Count(int start, int end)
    {
        return Count(start, end, 1);
    }
    static public IEnumerable<int> Count(int end)
    {
        return Count(1, end, 1);
    }
    static public IEnumerable<int> Count(int start, int end, int step)
    {
        for(int i = start; i <=end; i+=step)
            yield return i;
    }
}
Also, I should point out that the idea behind this came from a C++ iterator that I first saw presented by Andy Koenig. kick it on DotNetKicks.com
Share this post: Email it! | bookmark it! | digg it! | reddit!
Readability Stats: Word Count: 195; Sentence Count: 7; Grade Level: 9.7, more info...
Published Tuesday, May 08, 2007 12:30 PM by James

Comments

# re: More Fun with C# Interators : A Counting Iterator

Glad I was able to help :-)

Wednesday, May 09, 2007 4:39 PM by Michael Herman (Parallelspace)

# More Fun with C# Interators : A Counting Iterator

You've been kicked (a good thing) - Trackback from DotNetKicks.com

Thursday, May 10, 2007 7:55 AM by DotNetKicks.com

# re: More Fun with C# Interators : A Counting Iterator

....and that's better than using a for loop??

Friday, May 18, 2007 10:24 AM by Mike

# re: More Fun with C# Interators : A Counting Iterator

Mike:

The first example is clearly pointless.  It just exist to show the features,despite there being easier ways to accomplish the same thing.

However, I think you'd recognize the second example as simplier than the alternates.

Friday, May 18, 2007 12:05 PM by James
New Comments to this post are disabled