Yield return usage analysis in C # (reprinted from shichen2014)

Source: Internet
Author: User

This example describes the yield return usage in C #, and compares the use of yield return with no yield return for a better understanding of the reader. Specific as follows:

The yield keyword is used to iterate through the loop, and yield return is used to return the Ienumerable<t>,yield break used to terminate the loop traversal.

There is a collection of such an int type:

?
1234 staticList<int> GetInitialData(){  return newList<int>(){1,2,3,4};}

You need to print out all elements with values greater than 2.

Implementations that do not use yield return

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

Client calls:

?
12345678 staticvoid Main(string[] args){  foreach (var item inFilterWithoutYield())  { Console.WriteLine(item);  }  Console.ReadKey(); }

Output Result: 3,4

Use Yeild return to implement

?
123456789101112 static IEnumerable<int> FilterWithYield(){  foreach (int i in GetInitialData())  { if (i > 2) {   yield return i; }  }  yield break;  Console.WriteLine("这里的代码不执行");}

Client calls:

?
12345678 staticvoid Main(string[] args){  foreach (var item inFilterWithYield())  { Console.WriteLine(item);  }  Console.ReadKey(); }

Output Result: 3,4

Summarize:

Discover with one-step debugging:

Although the output of the 2 methods is the same, the operating process is very different. The first method is to load the result set into memory and then traverse it, and the second method, each time the client calls, yields return a value to the client, which is "supply on demand".

The first method, the client invocation process is roughly:

With yield return, the client invocation process is roughly:

Why is the use of yield return guaranteed to start executing once every time the loop is traversed?

--Because the compiler generates a state machine to maintain the state of the iterator.

Simply put, when you want to get a collection of ienumerable<t> types instead of loading the data into memory at once, consider using yield return for "on demand".

I hope this article is helpful to everyone's C # programming.

Yield return usage analysis in C # (reprinted from shichen2014)

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.