×

c# · level 3 · unit 4 · lesson 4

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

Extension methods plus yield make your own LINQ.

Put the last three lessons together. A generic extension method on IEnumerable<T> that uses yield return is a , exactly like the built-in ones. It is lazy, it works on a sequence of any type, and it chains with Where, Select and friends.

The shape is always the same: public static IEnumerable<T> EveryOther<T>(this IEnumerable<T> items). Inside, loop over items, decide what to pass on, and yield return it. Extension methods only appear where their namespace is brought in with using.

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

var queue = new[] { "Ana", "Ben", "Cy", "Dee", "Eve" };
Console.WriteLine(string.Join(" ", queue.EveryOther()));
var tens = Enumerable.Range(1, 10).EveryOther().Select(n => n * 10);
Console.WriteLine(string.Join(" ", tens));

static class MoreLinq
{
    public static IEnumerable<T> EveryOther<T>(this IEnumerable<T> items)
    {
        bool keep = true;
        foreach (T item in items)
        {
            if (keep)
            {
                yield return item;
            }
            keep = !keep;
        }
    }
}

Enumerable.Range(1, 10) counts from 1 up to 10, as a sequence.