Analysis of yield return usage in C,

Source: Internet
Author: User

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;

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.