C# 3.0

Page 222

Remember that query expressions are not activated until an iterator uses them.

So, it is only when we get to: foreach (Person p in selection) Console.Write(p+" "); Console.WriteLine("\n");

that the people in the tree are enumerated and filtered, producing finally: [Carrie, 2005]

[James, 2002]

[Sarah, 2000]

The full program for this example is in the Appendix. Further examples of iterators will be given in the programs that follow. In the past, there were many implementation issues to consider with iterators. They have mostly been covered with C# 3.0’s query expressions, a very powerful and user-friendly concept (see the earlier sidebar).

Use The Iterator pattern defines a fundamental separation between the iteration process and the enumeration process. Even in trivial cases the separation is advantageous, but its benefits are really felt when: • The structure is complex. • Different iterations are required over it, potentially at the same time. • The same structure and iterations can be applied to different data. It is important to keep clear the distinction (in the C# 3.0 context) between enumerators and iterators: Enumerators Provided by all the collections in the library, generic and nongeneric. They are supported by the IEnumerable interface and the yield return and yield break statements. Iterators Written by clients and supported by the foreach statement and query expressions. Loops pervade most code. Specifically, we would look to use an Iterator pattern with an iterator/enumerator mechanism when the conditions in the following table apply. Use the Iterator pattern when… You are iterating over a collection and one of these conditions holds: • There are various ways of traversing it (several enumerators). • There are different collections for the same kind of traversing. • Different filters and orderings might apply. Iterator Pattern |

199


Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.