Iterators in C#

CsharpProgrammingServer Side Programming

Iterator performs a custom iteration over a collection. It uses the yield return statement and returns each element one at a time. The iterator remembers the current location and in the next iteration the next element is returned.

The following is an example −

Example

 Live Demo

using System;
using System.Collections.Generic;
using System.Linq;

namespace Demo {
   class Program {
      public static IEnumerable<string> display() {
         int[] arr = new int[] {99,45,76};

         foreach (var val in arr) {
            yield return val.ToString();
         }
      }

      public static void Main(string[] args) {
         IEnumerable<string> ele = display();
         foreach (var element in ele) {
            Console.WriteLine(element);
         }
      }
   }
}

Output

99
45
76

Above, we have an iterator method display() that use the yield statement to return one element at a time −

public static IEnumerable<string> display() {
   int[] arr = new int[] {99,45,76};

   foreach (var val in arr) {
      yield return val.ToString();
   }
}

The result is stored and each element is iterated and printed −

IEnumerable<string> ele = display();
foreach (var element in ele) {
   Console.WriteLine(element);
}
raja
Published on 06-Aug-2018 09:23:26
Advertisements