
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
340
|
Chapter 6: Iterators and Partial Types
Solution
To add simple iterators that do not require parameters to be passed in to them, you
can add properties with a
get accessor. The get accessor must return an IEnumerable
type and make use of the yield return statement. Example 6-4 shows one way to
implement the solution.
Example 6-4. Adding multiple iterators that do not require parameters on a single type
public class SimpleListIterator
{
private List<string> _items = new List<string>( );
public void AddItem(string item)
{
_items.Add(item);
}
public IEnumerator GetEnumerator( )
{
for (int index = 0; index < _items.Count; index++)
{
yield return (_items[index]);
}
}
// Additional iterators implemented as property get accessors
public IEnumerable ReverseOrder
{
get
{
for (int index = _items.Count - 1; index >= 0; index--)
{
yield return (_items[index]);
}
}
}
public IEnumerable FirstHalf
{
get
{
for (int index = 0; index < (_items.Count / 2); index++)
{
yield return (_items[index]);
}
}
}
public IEnumerable SecondHalf
{
get
{