When to use yield return in C #

Source: Internet
Author: User

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.

 

There is a set of int types:

static List<int> GetInitialData()        {            return new List<int>(){1,2,3,4};        }

Print all elements with a value greater than 2.

 

Implementation of yield return is not used

static IEnumerable<int> FilterWithoutYield()        {            List<int> result = new List<int>();            foreach (int i in GetInitialData())            {                if (i > 2)                {                    result.Add(i);                }             }            return result;        }

Client call:

static void Main(string[] args)        {            foreach (var item in FilterWithoutYield())            {                Console.WriteLine(item);            }            Console.ReadKey();         }

Output result: 3, 4

 

Implementation Using yeild return

Static ienumerable <int> filterwithyield () {foreach (int I in getinitialdata () {if (I> 2) {yield return I ;}} yield break; console. writeline ("code not executed here ");}

Client call:

static void Main(string[] args)        {            foreach (var item in FilterWithYield())            {                Console.WriteLine(item);            }            Console.ReadKey();         }

Output result: 3, 4

 

Summary

Through one-step debugging, we found that:

Although the output results of the two methods are the same, the operation process is quite different. The first method is to load all the result sets to the memory and traverse them. The second method is to return a value to the client every time the client calls yield return, which is "supplied on demand ".


In the first method, the client call process is roughly as follows:

 

When yield return is used, the client call process is roughly as follows:

 

Why can I use yield return to ensure that execution starts from the previous stopped place during each loop traversal?

-- The compiler generates a state machine to maintain the iterator state.

 

To put it simply, if you want to obtain a set of ienumerable <t> types instead of loading data to the memory at a time, you can use yield return to implement "On-Demand Supply ".

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.