Exercises in this lecture   Go to the notes, in which this exercise belongs -- Keyboard shortcut: 'u'   Alphabetic index   Course home   

Exercise solution:
Explicit use of iterator - instead of using foreach


Here is my solution:

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;


class CollectionInterfaceDemo{

  public static void Main(){
    ICollection<Animal> lst = new Collection<Animal>();

    // Add elements to the end of the empty list:
    lst.Add(new Animal("Cat"));  lst.Add(new Animal("Dog", Sex.Female));
    lst.Add(new Animal("Mouse"));  lst.Add(new Animal("Rat"));
    lst.Add(new Animal("Mouse", Sex.Female));  lst.Add(new Animal("Rat"));
    lst.Add(new Animal("Herring", AnimalGroup.Fish, Sex.Female));  
    lst.Add(new Animal("Eagle", AnimalGroup.Bird, Sex.Male));   

    // Report in various ways on the animal collection:
    Print("Initial List", lst);
    ReportFemaleMale(lst);
    ReportGroup(lst);
  }

  public static void Print<T>(string explanation, ICollection<T> list){
    Console.WriteLine(explanation);
    IEnumerator<T> iterator = list.GetEnumerator();
    while(iterator.MoveNext()){
      Console.WriteLine("{0, 3}", iterator.Current);
    }
    Console.WriteLine(); Console.WriteLine();
  }

  public static void ReportFemaleMale(ICollection<Animal> list){
    int numberOfMales = 0,
        numberOfFemales = 0;

    IEnumerator<Animal> iterator = list.GetEnumerator();
    while(iterator.MoveNext()){
      if (iterator.Current.Sex == Sex.Male) numberOfMales++;
      else if (iterator.Current.Sex == Sex.Female) numberOfFemales++;
    }

    Console.WriteLine("Males: {0}, Females: {1}", 
                       numberOfMales, numberOfFemales);
  }

  public static void ReportGroup(ICollection<Animal> list){
    int numberOfMammals = 0,
        numberOfBirds = 0,
        numberOfFish = 0;

    IEnumerator<Animal> iterator = list.GetEnumerator();
    while(iterator.MoveNext()){
      if (iterator.Current.Group == AnimalGroup.Mammal) numberOfMammals++;
      else if (iterator.Current.Group == AnimalGroup.Bird) numberOfBirds++;
      else if (iterator.Current.Group == AnimalGroup.Fish) numberOfFish++;
    }

    Console.WriteLine("Mammals: {0}, Birds: {1}, Fish: {2}", 
                       numberOfMammals, numberOfBirds, numberOfFish);
  }

}