Information Technology Reference
In-Depth Information
Using an Iterator to Produce an Enumerable
You can use the enumerators and enumerables generated by iterators wherever you would use
manually coded enumerators or enumerables.
In the following example, iterators are used to produce an enumerable class. Class
ColorCollection has two enumerable iterators—one enumerating the items in forward order
and the other enumerating them in reverse order.
using System;
using System.Collections.Generic; // You need this namespace.
namespace ColorCollectionIterator {
class ColorCollection {
string[] Colors={"Red", "Orange", "Yellow", "Green", "Blue", "Purple"};
public IEnumerable<string> Forward() { // Enumerable iterator
for (int i = 0; i < Colors.Length; i++)
yield return Colors[i];
}
public IEnumerable<string> Reverse() { // Enumerable iterator
for (int i = Colors.Length - 1; i >= 0; i--)
yield return Colors[i];
}
}
class Program {
static void Main() {
ColorCollection cc = new ColorCollection();
Return enumerable to the foreach statement
foreach (string color in cc.Forward())
Console.Write("{0} ", color);
Console.WriteLine("");
Return enumerable to the foreach statement
foreach (string color in cc.Reverse())
Console.Write("{0} ", color);
Console.WriteLine("");
Search WWH ::




Custom Search