I know web pages should be past this, but this site doesn't look right on IE.
I will fix it some day ( not for IE 6 though) but for now this is easier and a lot more fun.

Download firefox or chrome or hide this message forever...
<< Back to blog main
090119.0

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.