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.