Analysis of yield return usage in _c# of wheel building

Source: Internet
Author: User

Site:

Http://www.jb51.net/article/54810.htm

static List< int > GetInitialData() {    return new List< int >(){1,2,3,4}; }Print out all elements with values greater than 2 implementations that do not use yield return static IEnumerable< int > FilterWithoutYield() {    List< int > result = new List< int >();    foreach ( int i in GetInitialData())    {   if (i > 2)   {     result.Add(i);   }    }    return result; } use yeild return to implement static IEnumerable< int > FilterWithYield() {    foreach ( int i in GetInitialData())    {   if (i > 2)   {     yield return i;   }    }    yield break ;    Console.WriteLine( "这里的代码不执行" ); }

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:

So,like This is cool:

        /// <summary>        ///recursive construction of commodity classification/// </summary>        /// <param name= "source" ></param>        /// <returns></returns>        PrivateIenumerable<productcategory> Recursioncategory (ienumerable<productcategoryext>source) {            if(source. Ishasrow ()) {foreach(varIteminchsource) {                    yield return NewProductCategory () {ParentID=item. ParentID, Cateid=item. ProductCategoryID, Catename=item. Vchmobileshowname, Icourl=item.                Catepic,}; }            }        }
View Code

Analysis of yield return usage in _c# of wheel building

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.