[Translation] yield statements in C # (useful LINQ statements)

Source: Internet
Author: User

Most of the time, we need to collect results based on certain conditions. For this reason, we need to create some set objects, insert and output them to these sets, and finally return the set. However, this is annoying.

One simple way to do this is to use the yield Statement (previously C #2.0 ). This keyword is used to return elements from a loop in a method and retain the state of the method for multiple calls.

Yield returns ienumerator or generic ienumerator <t>.

Public static IEnumerator <int> GetCounter ()
{
For (int count = 0; count <10; count ++)
{
Yield return count;
}
}

 

This will return the set IEnumerator <int>, which can be used to obtain the returned object.

 

IEnumerator <int> list = GetCounter ();
Console. Write (list. MoveNext () + "" + list. Current );

You can also have the yield break statement. If the yield break statement is executed in a method, the execution of this method is stopped and no return is returned. In this way, the first method can be rewritten as follows:

Public static IEnumerator <int> GetCounter ()
{
Int max = 10, min = 5;
While (true)
{
If (min> = max)
{
Yield break;
}
Yield return min ++;
}
}

Before I go deeper, it is worth remembering that in an iteration block, it is not just the operation from the beginning to the end. When the method was initially called, the iteration was just created. It is executed only when MoveNext () is called. At that time, execute from the beginning of the method as usual until the first yield return or yield break statement is processed or the end of the method is reached. At that time, a Boolean value is returned to show whether the statement block has completed iteration. If MoveNext () is called again, the method will continue to be executed only after the yield return statement. In each MoveNext () function and all MoveNext () function, the iteration function is called and the yield statement is executed from the previous yield to the next yield statement.

 

Code
Using system;
Using system. Collections. Generic;
Class Test
{
Static readonly string padding = new string ('', 30 );
Static ienumerator <int> getnumbers ()
{
Console. writeline ("first line of getnumbers ()");
Console. writeline ("just before yield return 0 ");
Yield return 10;

Console. writeline ("just after yield return 0 ");

Console. writeline ("just before yield return 1 ");
Yield return 20;
Console. writeline ("just after yield return 1 ");

}
Static void main ()
{
Console. writeline ("calling getnumbers ()");
Ienumerator <int> iterator = getnumbers ();
Console. writeline ("calling movenext ()");
Boolean more = iterator. movenext ();
Console. writeline ("result = {0}; current = {1}", more, iterator. Current );
Console. writeline ("calling movenext () again... ");
More = iterator. movenext ();
Console. writeline ("result = {0}; current = {1}", more, iterator. Current );
Console. writeline ("calling movenext () again... ");
More = iterator. movenext ();
Console. writeline ("result = {0} (stopping)", more );

}
}

------- Result
Calling GetNumbers ()
Calling MoveNext ()...
Firlst line of GetNumbers ()
Just before yield return 0
Result = True; Current = 10
Calling MoveNext () again...
Just after yield return 0
Just before yield return 1
Result = True; Current = 20
Calling MoveNext () again...
Just after yield return 1
Result = False (stopping)

Reference: http://csharpindepth.com/Articles/Chapter6/IteratorBlockImplementation.aspx

This is useful in the Linq query expression in C #3.0. It provides iterations in the Linq query.

Assume that there is a CustomerCollection class that contains a list of customers.

(IEnumerable <Customer> _ MERs mers)

 

Public class customercollection: ienumerable <customer>

This class is used in a LINQ query and iterated through the customer object contained in its list (_ customers). Therefore, the GetEnumerator method should be implemented as follows:

Public IEnumerator <Customer> GetEnumerator ()
{
Foreach (Customer customer in _ MERs mers)
Yield return customer;
}

 

From: http://munishbansal.wordpress.com/2008/09/12/yield-statement-in-c-useful-linq-statement/

 

This address may not be accessible.

Google snapshot address: http: // 203.208.37.132/search? Q = cache: egY7N3wP364J: Batch

 

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.