In C#, an Enumerator with the "yield" keyword is used to create an iterator method that simplifies the process of iterating over a collection of elements. The "yield" keyword allows you to define an iterator method by repeatedly yielding (returning) individual elements from the collection without explicitly creating an entire collection in memory. This approach is particularly useful for large or dynamically generated data sets, as it improves efficiency and memory usage.
By using "yield," you can create a custom iterator method that produces values one at a time, on-demand, while abstracting away the complexity of managing an explicit enumerator. This results in cleaner and more readable code for iterating through collections or sequences.
using System;
using System.Linq;
using System.Collections.Generic;
public class Program
{
public class Person
{
public int Id = 1;
public override string ToString() => $"Hey man {Id}";
}
public static void Main()
{
Console.WriteLine("Hello World");
IEnumerator<Person> people = CreateIterator(2);
while (people.MoveNext())
{
var item = people.Current;
Console.WriteLine(item.ToString());
break;
}
Console.WriteLine("again");
while (people.MoveNext())
{
var item = people.Current;
Console.WriteLine(item.ToString());
break;
}
}
public static IEnumerator<Person> CreateIterator(int givenCount)
{
var sequence = Enumerable.Range(1, givenCount);
foreach (var number in sequence)
{
Console.WriteLine($"count: {number}");
yield return new Person{Id = number};
}
}
}