Using Iterators in Collections

In some cases, the foreach instruction will not be appropriate for your collection handling requirements. For example, if you have a requirement to iterate through two collections simultaneously, the foreach instruction would not allow you to do this. In this case, you would need to use an Iterator object to read through a collection. For more details, see "Iterator Class", in Chapter 1 of the Encyclopaedia of Classes. See also "Using an as Clause in foreach Instructions", elsewhere in this chapter.

The following example uses an iterator to write out the name and ages of all employees in a supplied Employee dictionary.

writeEmployees(employees: EmployeeDict);
vars
    emp  : Employee;
    iter : Iterator;
begin
    iter := employees.createIterator;
    while iter.next(emp) do
        write emp.name & ", " & emp.calculateAge.String & " years";
    endwhile;
    delete iter;
end;