Mega Code Archive

 
Categories / C# / Class Interface
 

Iterates a collection forward and reverse

using System; using System.Collections.Generic; public class Starter {     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);         }     } } 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];             }         }     } }