Firstly we need to understand what yield return does.
The yield keyword returns elements from a collection without the need for a temporary collection.
Temporary Collection
Previously you would have done something similar to this.
- Create a temporary list of dogs
- Iterate through your list of pets
- Evaluate whether the pet is a dog. If true, add it to the list of dogs
- Once all pets have been checked, return the list of dogs to the calling method
public static IEnumerable GetDogs(IEnumerable pets){ List dogs = new List(); foreach (var pet in pets) { if(pet.Animal=="Dog") { dogs.Add(pet); } } return dogs; }
As you can imagine this can be very inefficient, especially if you have a large list of pets, where only a handful are dogs. Your code would still have to evaluate every pet.
In the code below, we want to grab 2 dogs from a list of pets. That sounds simple enough, but as you can see our code has to process every pet to decide whether it is a dog or not.
Yield Return
Yield return on the other hand can
- Iterate through your collection of pets 1 at a time
- Evaluate whether the pet is a dog.
- If it is, it will yield control back to the calling method whilst remembering it's position in the iteration.
- Once it has reached our request of finding 2 dogs, it will hand back control to the calling method without having to check the remaining pets. Drastically improving performance.
Here is an example showing this.
I hope this has made it a little easier to understand.