#1,196 – Using Fluent-Style Syntax when Chaining Iterators

You can chain iterator code together using a fluent-style syntax if you define extension methods for the corresponding IEnumerable<T> type that you’re using.  In the code below, we chain several iterators together, progressively filtering an IEnumerable<Dog> collection.

    class Program
    {
        static void Main(string[] args)
        {
            foreach (Dog d in AllMyDogs().YoungDogs().HerdingDogs())
            {
                Console.WriteLine(d);
                if (d.Breed == Breed.JackRussell)
                    break;
            }

            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, 19);
            yield return new Dog("Shep", Breed.Collie, 2);
            yield return new Dog("Foofoo", Breed.Sheltie, 8);
            yield return new Dog("Pongo", Breed.Dalmatian, 4);
            yield return new Dog("Rooster", Breed.WestHighlandTerrier, 1);
        }
    }

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

        public static IEnumerable<Dog> HerdingDogs(this IEnumerable<Dog> dogs)
        {
            foreach (Dog d in dogs)
                if ((d.Breed == Breed.BorderCollie) ||
                    (d.Breed == Breed.Collie) ||
                    (d.Breed == Breed.Sheltie))
                    yield return d;
        }
    }

Here’s the output:
1196-001

Advertisements