Yield return Simple example

Source: Internet
Author: User

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

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.