Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Iterator Functions in C#
An iterator method 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 display() {
int[] arr = new int[] {99,45,76};
foreach (var val in arr) {
yield return val.ToString();
}
}
public static void Main(string[] args) {
IEnumerable 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 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 ele = display();
foreach (var element in ele) {
Console.WriteLine(element);
}Advertisements