#1,194 – Chaining Iterators Together

An iterator can work on an IEnumerable<T>, using one sequence as input and generating a second sequence from the first.

In the example below, we use the output of one iterator as the input for another iterator.

        static void Main(string[] args)
        {
            IEnumerable<Dog> dogs1 = AllMyDogs();

            Console.WriteLine("============");
            foreach (Dog d in dogs1)
                Console.WriteLine(d);

            IEnumerable<Dog> dogs2 = YoungDogs(dogs1);

            Console.WriteLine("============");
            foreach (Dog d in dogs2)
                Console.WriteLine(d);

            IEnumerable<Breed> breeds = BreedsByNamePattern(dogs2, "oo");

            Console.WriteLine("============");
            foreach (Breed b in breeds)
                Console.WriteLine(b);

            Console.ReadLine();
        }

        private static IEnumerable<Dog> AllMyDogs()
        {
            yield return new Dog("Kirby", Breed.BorderCollie, 14);
            yield return new Dog("Jack", Breed.JackRussell, 15);
            yield return new Dog("Ruby", Breed.Mutt, 4);
            yield return new Dog("Lassie", Breed.Collie, 12);
            yield return new Dog("Foofoo", Breed.Sheltie, 8);
            yield return new Dog("Pongo", Breed.Dalmatian, 4);
            yield return new Dog("Rooster", Breed.WestHighlandTerrier, 1);
        }

        private static IEnumerable<Dog> YoungDogs(IEnumerable<Dog> dogs)
        {
            foreach (Dog d in dogs)
                if (d.Age < 10)
                    yield return d;
        }

        private static IEnumerable<Breed> BreedsByNamePattern(IEnumerable<Dog> dogs, string pattern)
        {
            foreach (Dog d in dogs)
                if (d.Name.Contains(pattern))
                    yield return d.Breed;
        }

1194-001

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

Leave a comment