Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
Iterators in C#
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
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);
} Advertisements
