CodeBlanks Logo Icon CodeBlanks

Summary - Advanced collections

C# course · Intermediate · Lesson 87/116

Combine IEnumerable, yield and custom collection to write a Range class.

Summary - Advanced collections

In this group you learned the foundation of iteration. IEnumerable<T> is the iterability contract, IEnumerator<T> is the lower layer, and yield return writes iterator methods concisely.

You can write your own collection with IEnumerable<T> and get array-based sorted access with SortedList<K,V>. Two small tasks now combine these tools.

Exercise Produce squares with yield

Write a Squares() method with return type IEnumerable<int> that produces 1, 4, 9 using yield return. In Main iterate and print with foreach.

Show example solution
Write Squares() returning IEnumerable<int>, put yield return 1; yield return 4; yield return 9; inside. In Main iterate with foreach.
Example solution:
using System;
using System.Collections.Generic;

class Program
{
    static IEnumerable<int> Squares()
    {
        yield return 1;
        yield return 4;
        yield return 9;
    }

    static void Main()
    {
        foreach (var s in Squares())
        {
            Console.WriteLine(s);
        }
    }
}

Exercise Read the first item with IEnumerator

Get an iterator from list below with GetEnumerator(). Call MoveNext() and print the Current value with Console.WriteLine.

Show example solution
Get the iterator with var e = list.GetEnumerator(); call e.MoveNext(); then write Console.WriteLine(e.Current);.
Example solution:
using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        var list = new List<int> { 7, 8, 9 };
        var e = list.GetEnumerator();
        e.MoveNext();
        Console.WriteLine(e.Current);
    }
}

The power of iteration

Knowing the iteration tools makes both built-in and custom collections flexible. A method taking IEnumerable<T> accepts any sequence; with yield return you produce large data in chunks.

The next section moves to advanced LINQ: operators like GroupBy, Join and Aggregate build on top of iteration.

Test yourself

  1. Which interface does foreach require?

    • IDisposable
    • IEnumerable<T>
    • IComparable
    • IClonable
    Show answer

    IEnumerable<T> — Correct. foreach works on types implementing IEnumerable<T>.

  2. Complete the yield statement

    yield____4;
    Show answer
    yieldreturn4;

All lessons in Intermediate