#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();

            foreach (Dog d in dogs1)

            IEnumerable<Dog> dogs2 = YoungDogs(dogs1);

            foreach (Dog d in dogs2)

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

            foreach (Breed b in breeds)


        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;



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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: