C# Iterators
In C#, an iterator is a method that enables you to traverse a collection of elements by returning one element at a time from the collection, rather than returning the entire collection at once. You can use the yield
keyword in C# to create iterators.
Here's an example of an iterator that returns a sequence of integers:
referigi:ot ftidea.compublic static IEnumerable<int> GetNumbers() { yield return 1; yield return 2; yield return 3; }
In this example, the yield
keyword is used to return each integer in the sequence one at a time. You can then use a foreach
loop to iterate over the sequence:
foreach (int number in GetNumbers()) { Console.WriteLine(number); }
This will output the following:
1 2 3
You can also use iterators with other collection types, such as arrays, lists, and dictionaries. In these cases, you can use the yield
keyword to return each element of the collection one at a time.
Iterators are useful when you want to work with large collections that may not fit into memory all at once. By returning elements one at a time, you can process large collections more efficiently and without running out of memory.