#1,196 – Using Fluent-Style Syntax when Chaining Iterators
October 3, 2014 6 Comments
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; } }
Pingback: Dew Drop – October 3, 2014 (#1869) | Morning Dew
This is super fun! I normally filter using lambda syntax, but it ends up looking quite ugly IMO:
foreach (Dog d in AllMyDogs()
.Where(dog => dog.Age youngDog.Breed == Breed.BorderCollie ||
youngDog.Breed == Breed.Collie ||
youngDog.Breed == Breed.Sheltie))
I love the look of your code much more. For readability, it definitely seems well worth the effort to write out the extra methods the way you did! Thanks for this!
Oops. Silly html interpreted part of my code as instructions. That should have read “.Where(dog => dog.Age < 10).Where(youngDog => youngDog.Breed”…
Testing…
foreach (var dog in MyDogs)
.Where(d => d.Bark == Bark.Loud)
.Where(loudDog => loudDog.AnnoysNeighborBob == true)
{ dog.KeepIndoors(); }
Testing again…
foreach (var dog in MyDogs)
.Where(d => d.BarkVolume !quietDog.LooksAtNeighborBobAggressively)
{ dog.SendOutdoors(); }
Thanks! Apologies if WordPress mangles your comments.