C# Iterators: Simplifying Collection Traversal
Learn how to use iterators in C# to efficiently traverse collections (arrays, lists). This tutorial explains the `yield return` statement, demonstrates creating custom iterators, and highlights their benefits for cleaner, more readable, and maintainable code when working with sequential data.
Understanding and Using Iterators in C#
Introduction
In C#, an iterator is a method that allows you to traverse the elements of a collection (like an array or list) one at a time. It uses the yield return
statement to return each element, remembering its position for the next iteration. Iterators simplify working with collections and improve code readability.
Key Features of Iterators
yield return
: This statement returns a single element and pauses execution, remembering its place. The next call to the iterator resumes from where it left off.yield break
: This statement stops the iteration.- Return Types: An iterator method typically returns
IEnumerable<T>
orIEnumerator<T>
.
Example 1: Iterating Through an Array
This example shows how to create an iterator that returns elements from an integer array.
Example 1: Array Iterator
using System;
using System.Collections.Generic;
namespace CSharpFeatures {
class IteratorExample {
public static IEnumerable<string> GetArray() {
int[] arr = new int[] { 5, 8, 6, 9, 1 };
foreach (var element in arr) {
yield return element.ToString();
}
}
public static void Main(string[] args) {
IEnumerable<string> elements = GetArray();
foreach (var element in elements) {
Console.WriteLine(element);
}
}
}
}
Output Example 1
5
8
6
9
1
Explanation Example 1
GetArray()
is the iterator. Each yield return
pauses execution and returns a string representation of the current array element. The Main
method iterates through the results.
Example 2: Iterating Through a List
This example demonstrates an iterator for a list of strings.
Example 2: List Iterator
using System;
using System.Collections.Generic;
namespace CSharpFeatures {
class IteratorExample {
public static IEnumerable<string> GetList() {
List<string> list = new List<string>();
list.Add("Rohan");
list.Add("Peter");
list.Add("Irfan");
list.Add("Sohan");
foreach (var element in list) {
yield return element;
}
}
public static void Main(string[] args) {
IEnumerable<string> elements = GetList();
foreach (var element in elements) {
Console.WriteLine(element);
}
}
}
}
Output Example 2
Rohan
Peter
Irfan
Sohan
Explanation Example 2
Similar to Example 1, but this iterator works with a list. The yield return
statement efficiently returns each list element one at a time.
Conclusion
Iterators provide a clean and efficient way to process collections in C#. The yield return
mechanism makes it easy to manage the iteration process and improves code readability.