c# · level 3 · unit 4 · lesson 4
- meet it
- guess first
- your turn
- fix it
- 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.
guess first
A running total. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
using System;
using System.Collections.Generic;
using System.Linq;
int[] deposits = { 5, 10, 20 };
Console.WriteLine(string.Join(" ", deposits.RunningTotal()));
Console.WriteLine(deposits.RunningTotal().Last());
static class MoreLinq
{
public static IEnumerable<int> RunningTotal(this IEnumerable<int> numbers)
{
int total = 0;
foreach (int n in numbers)
{
total += n;
yield return total;
}
}
}
your turn
Your turn. Build WhereNot.
On line 14, finish the test so WhereNot keeps only the items that fail test. Then on line 5, write your own lambda that picks the snacks to throw out.
output
press run to see what happens
fix it
The lap picker will not compile. Can you fix it?
output
press run to see what happens
- C# says the sequence has no
Selecton line 5. Where doesSelectcome from? Selectis an extension method, and extension methods only appear when their namespace is brought in.- Add
using System.Linq;under the otherusinglines, then run.
nailed it
you wrote your own query operators. :D
- A query operator is a generic extension with
yield return. - Your operators are lazy and chain with the built-in ones.
- Extension methods need their namespace brought in with
using.
new words in your collection
- query operator
This lesson isn’t saved. A free account remembers every lesson you finish.