Filtering and projection
Select makes a new shape
Where keeps or drops an item; Select replaces it. The lambda takes one item and returns something else: a property, a tuple, a string from an interpolation, an object of a new type. The result is a sequence of the new shape, and the original items are not changed.
A projection is the place to do the work that turns stored data into display data, once, instead of in every place that reads it:
var readings = new[] { 12, 15, 9, 21, 7, 18, 30 };
var report = readings.Select(r => new { Celsius = r, Fahrenheit = r * 9 / 5 + 32 });
foreach (var row in report)
{
Console.WriteLine($"{row.Celsius,3} C {row.Fahrenheit,4} F");
}
Console.WriteLine($"rows: {report.Count()}");
dotnet run
12 C 53 F
15 C 59 F
9 C 48 F
21 C 69 F
7 C 44 F
18 C 64 F
30 C 86 F
rows: 7
The anonymous type has two properties with the names given on the left of the equal sign, and the compiler generates a type for it. The integer division in r * 9 / 5 truncates, which is why 12 C becomes 53 F and not 53.6: a projection shows exactly the arithmetic that was written.
Select with an index
An overload of Select takes a second argument: the position of the item in the source, counted from zero. The same overload exists on Where, where it lets a query keep every other item:
var cities = new[] { "Oslo", "Lima", "Kyiv", "Rome" };
var numbered = cities.Select((city, index) => $"{index + 1}. {city}");
Console.WriteLine(string.Join(Environment.NewLine, numbered));
dotnet run
1. Oslo
2. Lima
3. Kyiv
4. Rome
The index is a position in the source sequence, not in the result, and it counts what the previous steps produced: a Where before the Select renumbers the survivors from zero. That is what makes Where((item, i) => i % 2 == 0) keep alternate items instead of every item at an even position of the result.
Distinct and an anonymous type
Distinct drops repeated items and keeps the first occurrence. For a string it compares ordinal characters, so apple and Apple are two different items; a case-insensitive version passes StringComparer.OrdinalIgnoreCase.
var words = new[] { "apple", "Apple", "banana", "banana", "cherry", "avocado" };
var distinct = words.Distinct();
var longWords = distinct
.Where(w => w.Length > 5)
.Select(w => new { Word = w, Length = w.Length })
.OrderBy(x => x.Length)
.ThenBy(x => x.Word);
Console.WriteLine(string.Join(", ", distinct));
foreach (var item in longWords)
{
Console.WriteLine($"{item.Word}: {item.Length}");
}
Console.WriteLine($"distinct {distinct.Count()} long {longWords.Count()}");
dotnet run
apple, Apple, banana, cherry, avocado
banana: 6
cherry: 6
avocado: 7
distinct 5 long 3
Six words became five: the second banana went, and the two spellings of apple both stayed. Three of the five are longer than five characters, and the two of length six are ordered by the tie-break.
A value captured by the lambda
A lambda may read a local variable of the enclosing method. The compiler captures it, and because the query is deferred, it reads the value the variable has at the walk, not the value it had when the query was written:
var readings = new[] { 12, 15, 9, 21, 7, 18, 30 };
var threshold = 14;
var above = readings
.Where(r => r > threshold)
.Select(r => new { Value = r, Over = r - threshold });
Console.WriteLine($"threshold {threshold}");
foreach (var item in above)
{
Console.WriteLine($"{item.Value} is {item.Over} over");
}
Console.WriteLine($"kept {above.Count()} of {readings.Length}");
dotnet run
threshold 14
15 is 1 over
21 is 7 over
18 is 4 over
30 is 16 over
kept 4 of 7
Four readings are above 14, and each line subtracts the same 14 that was printed. Move the assignment of threshold below the query and the compiler refuses the program with error CS0841: a local variable cannot be used before it is declared, lazy or not. Assign it a new value after the query and the query uses that new value at the walk.
Exercises
- Project the readings into a named record instead of an anonymous type and keep the query working.
- Keep every second city with the index overload of Where.
- Make Distinct ignore case and print the five items that remain.
- Change threshold after the query is declared but before the foreach. Which lines print, and why?
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does Select change about a sequence?
Answer
Each item, through a function of that item
Select is a projection: one output item per input item, produced by the lambda.
-
Which overload of Select takes an index?
Answer
Select((item, index) => ...)
The func form takes the item and its zero-based position in the source sequence.
-
What does this program print?
var w = new[] { "a", "a", "bb" }; var d = w.Distinct(); Console.WriteLine(string.Join(",", d));Answer
a,bb
Distinct keeps the first occurrence of each item, so the second a is dropped.
-
What does Distinct do with "apple" and "Apple"?
Answer
Keeps both, because the default comparison is ordinal and case-sensitive
The default comparer for string is ordinal, so the two spellings differ.
-
A query reads a captured local. Which value does it use?
Answer
The value at the moment of the walk
The lambda captures the variable, not a copy, and deferred execution reads it at the walk.
-
What does
Select((x, i) => i)over three items return?Answer
0, 1, 2
The index is zero-based, so three items give the positions zero, one and two.
-
Where in a projection should formatting happen?
Answer
Once, in the Select that produces the display shape
A projection turns stored data into display data once, and each reader uses the result.
-
What does this program print?
var n = new[] { 1, 2, 3, 4 }; Console.WriteLine(string.Join(",", n.Where(x => x % 2 == 0).Select(x => x * x)));Answer
4,16
The filter keeps 2 and 4, and the projection squares each of them.
-
What is the type of
new { Celsius = r }in a Select?Answer
An anonymous type generated by the compiler, with a Celsius property
The compiler creates a type with a read-only property per name, usable inside the method only.
-
What does a Where before a Select do to the index of the Select?
Answer
Renumbers the survivors from zero
The index is a position in the sequence the operator receives, which is the filtered one.
The code on this page was built with the .NET SDK 10.0.303 and run on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev