C# .NET Iterator Example : Reverse Iteration
The following example iterates a collection forward and reverse. Two iterators are exposed for this reason. GetEnumerator exposes the standard forward iterator. The reverse iterator is implemented in the Reverse property. Because the property returns IEnumerable, the Reverse property is both an enumerable and enumerator object. When an iterator method returns IEnumerable, the nested class generated by the compiler is implemented as both an enumerable and enumerator object. In Main, there are two foreach loops: The first foreach loop uses the forward iterator, whereas the reverse iterator is requested in the second loop:
|
using System; using System.Collections.Generic;
namespace Examples.Iterators { public class Program { public static void Main() { Console.WriteLine(“Forward List”); MyClass obj = new MyClass(); foreach (int item in obj) { Console.Write(item); }
Console.WriteLine(“\nReverse List”); foreach (int item in obj.Reverse) { Console.Write(item); }
Console.ReadKey(); } }
public class MyClass { private int[] list1 = new int[] { 0, 2, 4, 6, 8 };
public IEnumerator<int> GetEnumerator() { for (int index = 0; index < 5; ++index) { yield return list1[index]; } }
public IEnumerable<int> Reverse { get { for (int index = 4; index >= 0; –index) { yield return list1[index]; } } } } } |
-
Archives
- February 2009 (1)
- November 2008 (6)
- October 2008 (4)
- September 2008 (13)
- August 2008 (11)
- July 2008 (29)
- June 2008 (19)
- May 2008 (8)
-
Categories
-
RSS
Entries RSS
Comments RSS

