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)) ...
Get C# 3.0 Cookbook, 3rd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.