yield filters
I recently discovered the yield keyword combined with IEnumerable functions in C#. It is a great way to filter lists of items.
For example:
private void SomeFunction(){
//some code
foreach (Animal a in FilterAnimals(animals, 2, true)){
// do something with each two legged, winged animal
}
//some more code
}
private IEnumerable<Animal> FilterAnimals(List<Animal> animals, int legs, bool hasWings){
foreach (Animal a in animals){
if (a.Legs == legs && a.HasWings == hasWings){
yield return a;
}
}
}
The first time I saw this, I thought it was an N 2 loop. However, the yield preserves the state of the function so the whole list is only looped over once. The original list of animals is still the same as it was before.