6.3. Creating Custom Enumerators
Problem
You need to add foreach support to a class, but the normal way of adding an iterator (i.e., implementing IEnumerable on a type and returning a reference to this IEnumerable from a member function) is not flexible enough. Instead of simply iterating from the first element to the last, you also need to iterate from the last to the first, and you need to be able to step over, or skip, a predefined number of elements on each iteration. You want to make all of these types of iterators available to your class.
Solution
The Container<T> class shown in Example 6-1 acts as a container for a private List<T> called internalList. Container is implemented so you can use it in a foreach loop to iterate through the private internalList.
Example 6-1. Creating custom iterators
public class Container<T> : IEnumerable<T> { public Container() {} private List<T> _internalList = new List<T>(); // This iterator iterates over each element from first to last public IEnumerator<T> GetEnumerator() { return _internalList.GetEnumerator(); } // This iterator iterates over each element from last to first public IEnumerable<T> GetReverseOrderEnumerator() { foreach (T item in ((IEnumerable<T>)_internalList).Reverse()) { yield return item; } } // This iterator iterates over each element from last to first stepping // over a predefined number of elements public IEnumerable<T> GetReverseStepEnumerator(int step) { foreach (T item in ((IEnumerable<T>)_internalList).Reverse().EveryNthItem(step)) ...Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access