#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

Advertisements

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

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 )

Google+ photo

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

Connecting to %s

%d bloggers like this: