📝 How to implement the Where method in C#?



The
yield keyword actually does quite a lot here. It creates a state machine "under the covers" that remembers where you were on each additional cycle of the function and picks up from there.



The function returns an object that implements the IEnumerable<T> interface. If a calling function starts foreaching over this object, the function is called again until it "yields" result based on some predicate.



This is syntactic sugar introduced in C# 2.0. In earlier versions you had to create your own IEnumerable and IEnumerator objects to do stuff like this.



#post