
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
330
|
Chapter 6: Iterators and Partial Types
IEnumerable from a member function) is not flexible enough. Instead of simply iterat-
ing 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-2 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-2. Creating custom iterators
public class Container<T>
{
public Container( ) {}
private List<T> internalList = new List<T>( );
public List<T> List
{
set {internalList = value;}
}
// This iterator iterates over each element from first to last.
public IEnumerator<T> GetEnumerator( )
{
for (int index = 0; index < internalList.Count; index++)
{
yield return (internalList[index]);
}
}
// This iterator iterates over each element from last to first.
public IEnumerable<T> ReverseOrder
{
get
{
for (int index = internalList.Count - 1; index >= 0; index--)
{
yield return (internalList[index]);
}
}
}
// This iterator iterates over each element from first to last stepping
// over ...