Iterator Pattern in C# – Real-Time Example (Sequential Collection Traversal)

What is Iterator Pattern?

The Iterator Pattern is a behavioral design pattern that provides a way to access elements of a collection sequentially without exposing its internal structure.

👉 Helps traverse collections safely and uniformly.


Why Use Iterator Pattern?

  • Simplify collection traversal
  • Hide internal collection structure
  • Provide uniform access to elements
  • Support custom iteration logic
  • Improve maintainability

Real-Time Scenario

Examples:

  • Pagination in APIs
  • Traversing invoice items
  • Navigating product lists
  • Iterating menu items

👉 Client accesses items one by one without knowing collection internals.


Real-Time Example – Product Collection


Step 1: Collection Class


public class ProductCollection
{
    private readonly List<string> _products = new();

    public void Add(string product)
    {
        _products.Add(product);
    }

    public Iterator GetIterator()
    {
        return new Iterator(_products);
    }
}

Step 2: Iterator Class


public class Iterator
{
    private readonly List<string> _products;
    private int _position = 0;

    public Iterator(List<string> products)
    {
        _products = products;
    }

    public bool HasNext()
    {
        return _position < _products.Count;
    }

    public string Next()
    {
        return _products[_position++];
    }
}

Usage Example


var products = new ProductCollection();

products.Add("Laptop");
products.Add("Mobile");
products.Add("Keyboard");

var iterator = products.GetIterator();

while (iterator.HasNext())
{
    Console.WriteLine(iterator.Next());
}

Output


Laptop
Mobile
Keyboard

Key Concept

Instead of:


for(int i = 0; i < list.Count; i++)
{
}

We do:


iterator.Next();

👉 Iteration logic encapsulated separately.


Diagram Understanding


Client
   ↓
Iterator
   ↓
Collection

👉 Iterator controls traversal.


Advantages

  • ✔ Simplifies traversal
  • ✔ Hides internal structure
  • ✔ Supports custom iteration
  • ✔ Cleaner code
  • ✔ Multiple iterators possible

Disadvantages

  • ✖ Additional classes
  • ✖ Can increase complexity
  • ✖ Less useful for simple collections

When to Use

Use Iterator Pattern when:

  • Traversing complex collections
  • Internal structure should remain hidden
  • Multiple traversal methods are needed
  • Sequential access is important

Real Project Mapping (.NET + Angular)

Feature Usage
Pagination Iterator
Product listing Iterator
Invoice items traversal Iterator
Tree navigation Iterator
Data streaming Iterator

ASP.NET Core Real Example

IEnumerable / IEnumerator


foreach(var item in products)
{
    Console.WriteLine(item);
}

👉 .NET collections internally use Iterator Pattern.


Advanced Example – API Pagination


Page 1 → Page 2 → Page 3

👉 Iterator moves through paginated data sequentially.


Iterator vs Composite

Iterator Composite
Traverses collection Represents tree structure
Focus on navigation Focus on hierarchy
Sequential access Parent-child relationships

Pro Tip

Iterator Pattern works well with:

  • IEnumerable
  • LINQ
  • Pagination systems
  • Streams
  • Recursive collections

Summary

Iterator Pattern helps you:

  • Traverse collections cleanly
  • Hide collection internals
  • Simplify sequential access

👉 Perfect for:

  • Pagination
  • Product lists
  • Data traversal
  • Collection processing

Comments

Popular posts from this blog

Promises in Angular

Debouncing & Throttling in RxJS: Optimizing API Calls and User Interactions

Csharp Coding - Session