. 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.