December 2007
Intermediate to advanced
896 pages
19h 57m
English
Iterators need to provide access to the data elements in the collections they are implemented for. You need a good way to work with sets of data.
Use LINQ to implement iterator logic, as shown in Example 6-2. The highlighted items are just a few parts of LINQ that can help you with the implementation of iterator logic.
Example 6-2. Implementing iterator logic with LINQ
public class SectionalList<T> : IEnumerable<T>
{
private List<T> _items = new List<T>();
public void Add(T item)
{
_items.Add(item);
}
public IEnumerator<T> GetEnumerator()
{
return _items.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public IEnumerable<T> GetFirstHalf()
{
foreach(T item in _items.Take(_items.Count / 2))
{
yield return item;
}
}
public IEnumerable<T> GetSecondHalf()
{
foreach (T item in _items.Skip(_items.Count / 2))
{
yield return item;
}
}
public IEnumerable<T> GetFilteredValues(Func<T, bool> predicate)
{
foreach (T item in _items.TakeWhile(predicate))
{
yield return item;
}
}
public IEnumerable<T> GetReverseFilteredValues(Func<T, bool> predicate)
{
foreach (T item in _items.SkipWhile(predicate))
{
yield return item;
}
}
}The SectionalListat class contains the typical GetEnumerator iterator method that yields all items in the _items list. In addition to this iterator method, the class contains four additional iterators: GetFirstHalf, GetSecondHalf, GetFilteredValues, and GetReverseFilteredValues.
The ...
Read now
Unlock full access