How to use iterators to iterate through a collection in C#?

In C#, iterators can be used to traverse collections. They are a special type of method that allows us to sequentially access the elements in a collection without exposing the internal implementation details of the collection.

The steps for traversing a collection using an iterator are as follows:

  1. Implement a method in the collection class that returns an iterator, typically named GetEnumerator(), and returns an iterator object that implements the IEnumerable interface.
  2. Use the yield keyword in an iterator object to return elements from a collection. Yield keyword can transform the current method into an iterator, allowing it to return an element each time a loop iteration occurs.
  3. Use a foreach loop in the caller’s code to iterate through the elements in the collection.

Here is a simple example demonstrating how to use an iterator to traverse a collection of integers.

using System;
using System.Collections;
using System.Collections.Generic;

public class MyCollection : IEnumerable<int>
{
    private List<int> list = new List<int>();

    public MyCollection()
    {
        list.Add(1);
        list.Add(2);
        list.Add(3);
        list.Add(4);
    }

    public IEnumerator<int> GetEnumerator()
    {
        foreach (int i in list)
        {
            yield return i;
        }
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }
}

class Program
{
    static void Main()
    {
        MyCollection collection = new MyCollection();

        foreach (int i in collection)
        {
            Console.WriteLine(i);
        }
    }
}

In this example, the MyCollection class implements the IEnumerable interface and uses the yield keyword in the GetEnumerator() method to return elements from the integer collection. In the Main method, we use a foreach loop to iterate through the MyCollection object and print out each integer element.

Leave a Reply 0

Your email address will not be published. Required fields are marked *