CSharp · Console
using System;
using System.Collections.Generic;
using System.Linq;
public class Program
{
public static void Main()
{
//obtain a list of pets
IEnumerable<Pet> pets = CreateListOfPets();
//pass the pets list into our GetDogs method and yield return the first 2 dogs we find.
foreach (var dog in GetDogsUsingYield(pets).Take(2))
{
Console.WriteLine("- retrieved: " + dog.Name + " the " + dog.Animal);
}
}
public static IEnumerable<Pet> GetDogsUsingYield(IEnumerable<Pet> pets){
foreach (var pet in pets)
{
Console.WriteLine("Processing with yield: " + pet.Animal);
if(pet.Animal=="Dog")
{
Console.WriteLine("yielding: " + pet.Animal);
yield return pet;
}
}
}
public static IEnumerable<Pet> CreateListOfPets(){
return new List<Pet>{
new Pet{Animal="Dog",Colour="Black", Name="Rocky"},
new Pet{Animal="Cat",Colour="Black", Name="Betty"},
new Pet{Animal="Dog",Colour="White", Name="Fluffy"},
new Pet{Animal="Elephant",Colour="Grey", Name="Nellie"},
new Pet{Animal="Dog",Colour="Brown", Name="Lassie"},
new Pet{Animal="Cat",Colour="Brown", Name="Mr Jinx"},
new Pet{Animal="Mouse",Colour="Brown", Name="Micky"},
new Pet{Animal="Cat",Colour="Black", Name="Tom"},
new Pet{Animal="Turtle",Colour="Green", Name="Leonardo"},
new Pet{Animal="Yoda",Colour="Brown", Name="Lizard"}
};
}
}
public class Pet{
public string Animal {get;set;}
public string Colour {get;set;}
public string Name {get;set;}
}