public class Animals : List<Animal>
{
public IEnumerable GetMammals()
{
foreach (Animal _Animal in this)
{
if (_Animal.Type == "Mammal")
yield return _Animal;
}
}
}
See that method called GetMammals()? That’s all there is to it. You use the combination of “yield return” to return members of the iterator or “yield break” to stop the processing in the method.
You use it in any old for each statement like this:
foreach (Animal a in List.GetMammals())
It’s so easy – now think further and add parameters to filter or sort and now you see why this exists.