Analysis of yield return usage in C,
Note: The yield keyword is used to traverse the loop. The yield return is used to return IEnumerable <T> and the yield break is used to terminate the loop traversal.
The following compares the use of yield return and the use of yield return, directly on the Code:
Using System; using System. collections. generic; namespace ConsoleApp {class Program {static void Main (string [] args) {Console. writeLine ("results without using the yield return method"); foreach (var item in WithoutYield () {Console. writeLine (item);} Console. writeLine ("results using the yield return method"); foreach (var item in WithYield () {Console. writeLine (item);} Console. readLine ();} /// <summary> /// do not use yield return // </summary> /// <returns> </returns> static IEnumerable <int> WithoutYield () {List <int> result = new List <int> (); foreach (int I in GetData () {if (I> 2) {result. add (I) ;}} return result ;} /// <summary> /// use yield return // </summary> /// <returns> </returns> static IEnumerable <int> WithYield () {foreach (int I in GetData () {if (I> 2) {yield return I ;}} yield break; Console. writeLine ("code not executed here ");} /// <summary> /// obtain data /// </summary> /// <returns> </returns> static List <int> GetData () {return new List <int> () {1, 2, 3, 4 };}}}
The output result is as follows:
Summary:
Debugging shows that the output results of the two methods are the same, but the actual operation process is different.
The first method is to load all the result sets to the memory and traverse them;
Method 2: traverse every call, and yield return returns a value;
Therefore, if you want to obtain an IEnumerable <T> type set and do not want to load the data to the memory at a time, you can use yield return;