. NET-based iterator and. net-based iterator

Source: Internet
Author: User

. NET-based iterator and. net-based iterator

The foreach loop is implemented using the IEnumerator interface. IEnumerator implements the iterator. In foreach, how does one iterate an arrayList set?

Implementation example of the iterator:

class Program    {                public static void Main(string[] args)        {            foreach (string str in SimpleList())            {                Console.WriteLine(str);            }            Console.ReadKey();        }        public static IEnumerable SimpleList()        {            yield return "1";            yield return "2";            yield return "3";        }    }
In this way, we have implemented the simplest iterator. Result: public static void Main (string [] args) {Primes primesFrom2TO1000 = new Primes (2, 1000); foreach (long I in primesFrom2TO1000) {Console. write ("{0}", I );}}
Public class Primes {private long min; private long max; public Primes (): this (2,200) {} public Primes (long minimum, long maximum) {if (minimum <2) {min = 2;} else {min = minimum;} max = maximum;} public System. collections. IEnumerator GetEnumerator () // The return type is an iterator {for (long possiblePrime = min; possiblePrime <= max; possiblePrime ++) {bool isPrime = true; for (long possibleFactor = 2; possibleFactor <= (long) Math. floor (Math. sqrt (possiblePrime); possibleFactor ++) {long remainderAfterDivsion = possiblePrime % possibleFactor; if (remainderAfterDivsion = 0) {isPrime = false; break;} if (isPrime) {yield return possiblePrime; // returns a prime number }}}}

Result:

 

There are two types returned by the iterator: IEnumberable and IEnumerator.

  • To iterate a class, you can use GetEnumerator (). Its return type is IEnumerator.
  • If you want to iterate a class member, such as a method, use IEnumerable.

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.