iterates a collection forward and reverse : IEnumerable « Class Interface « C# / C Sharp






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];
            }
        }

    }
}

 








Related examples in the same category

1.yield return
2.return IEnumerable
3.Return IEnumerable by yield
4.Extends IEnumerable
5.IEnumerable with a foreach loop
6.Enumerator Example (Versioned Collection)
7.Tree Enumerator