list<int> list =Newlist<int>() { 1,2,3,4 }; //demand: Returns all numbers greater than n//Method 1 (Do not use yield return)ienumerable<int> Withoutyield (list<int> list,intN) {List<int> result =Newlist<int>(); foreach(intIinchlist) { if(I >N) {result. ADD (i); } } returnresult; } //Method 2 (use yield return)ienumerable<int> Useyieldreturn (list<int> list,intN) {foreach(intIinchlist) { if(I >N) {yield returni; } } }
//called voidCall () {foreach(intIinchWithoutyield (list,2) {Console.WriteLine (i+"without yield"); } foreach(intIinchUseyieldreturn (list,2) {Console.WriteLine (i+"With yield"); } }
Difference: Method 1 is to load all the numbers greater than n into memory first
Method 2 is to return a value once per call, which is supplied on demand
Conclusion: To get a collection of ienumerable<t> types, but do not want to load the data into memory at once, you can use yield return to achieve on-demand supply
Popular understanding: After yield return, the next time you call this method, the last yield return from the place to continue execution (before the last yield return code in this call does not execute ~ ~).
You can exit an iteration by using yield break.
Yield return Simple example