SelectMany and null in a query
Flattening with SelectMany
Select gives one output item per input item, so a sequence of sequences stays a sequence of sequences. SelectMany takes one sequence per item and joins them into one flat result, which is the operation a nested foreach writes by hand.
var nested = new[] { new[] { 1, 2 }, new[] { 3 }, Array.Empty<int>() };
var flat = nested.SelectMany(inner => inner);
Console.WriteLine(string.Join(",", flat));
Console.WriteLine($"count {flat.Count()} outer {nested.Length}");
dotnet run
1,2,3
count 3 outer 3
Three outer arrays became three items, not six: the empty array contributes nothing and is not an error. The source order is kept, so the items of the first array come before those of the second.
SelectMany with a result selector
A second overload takes a result selector with the outer item and the inner item, which is how a parent is kept next to each child. This is the method form of two nested loops that produce one row per pair:
var teams = new[]
{
new Team("core", new[] { "Anna", "Borys" }),
new Team("web", new[] { "Clara" }),
new Team("ops", new[] { "Danylo", "Elena", "Farid" }),
};
var members = teams
.SelectMany(team => team.Members, (team, member) => $"{member} ({team.Name})")
.OrderBy(line => line);
Console.WriteLine(string.Join(Environment.NewLine, members));
Console.WriteLine($"members: {members.Count()}");
record Team(string Name, string[] Members);
dotnet run
Anna (core)
Borys (core)
Clara (web)
Danylo (ops)
Elena (ops)
Farid (ops)
members: 6
Six names from three teams, each with its team in brackets. In query syntax the same thing is a second from: from team in teams from member in team.Members select .... The compiler turns that second from into SelectMany, which is why the two forms are the same query.
FirstOrDefault
First throws when the sequence is empty; FirstOrDefault returns the default value of the item type: null for a class, and zero for a number. The number is the one that hides a bug, because zero is also a real value:
var names = new List<string> { "Anna", "Borys" };
var scores = new List<int> { 91, 78 };
string? missing = names.FirstOrDefault(n => n.StartsWith("Z"));
string? found = names.FirstOrDefault(n => n.StartsWith("B"));
int score = scores.FirstOrDefault(s => s > 100);
Console.WriteLine($"missing: {missing ?? "<none>"}");
Console.WriteLine($"found: {found} length {found?.Length ?? 0}");
Console.WriteLine($"score: {score}");
dotnet run
missing: <none>
found: Borys length 5
score: 0
No name starts with Z, so the string version returned null and ?? printed the placeholder. The number version returned 0, which looks exactly like a score of zero: for a number, a nullable item type is the honest choice. int? makes the miss visible and the compiler insist on a check before the value is used.
A nullable chain
The two operators of the previous program are the tools for a chain of values that may be missing:
- ?. calls a member only when the receiver is not null, and the result is nullable.
- ?? replaces a null result with a value of the same type.
- ??= assigns only when the variable is null.
var scores = new Dictionary<string, int>
{
["Anna"] = 91,
["Borys"] = 78,
["Clara"] = 85,
};
int? borys = Lookup("Borys");
int? danylo = Lookup("Danylo");
Console.WriteLine($"borys {borys ?? -1}");
Console.WriteLine($"danylo {danylo ?? -1}");
Console.WriteLine($"missing length: {Find("Danylo")?.Length ?? 0}");
int? Lookup(string name) => scores.TryGetValue(name, out var score) ? score : null;
string? Find(string name) => scores.ContainsKey(name) ? name : null;
dotnet run
borys 78
danylo -1
missing length: 0
A lookup that misses returns null, not zero, and ?? decides what a miss prints. The last line chains both: Find returns string?, ?. reads Length only when it is not null, and ?? turns the missing length into 0. One line, no if, and the compiler checks the whole chain.
Exercises
- Flatten the nested arrays and print only the numbers above one.
- Write the teams query with a second from and check that the result is the same.
- Change the score line to int? score and print the miss as no score.
- Add an ??= to the dictionary program that fills a missing score with zero only when it is absent.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does SelectMany do with a sequence of sequences?
Answer
Joins the inner sequences into one flat sequence
SelectMany projects each item to a sequence and concatenates the results.
-
What does
FirstOrDefaultreturn when nothing matches and the items are numbers?Answer
Zero, the default of the type
The default value of an int is 0, which is why a nullable item type is safer for numbers.
-
What does this program print?
var n = new[] { new[] { 1 }, new[] { 2, 3 } }; Console.WriteLine(string.Join(",", n.SelectMany(x => x)));Answer
1,2,3
SelectMany flattens the two inner arrays into one sequence of three items.
-
What does
value?.Lengthgive when value is null?Answer
null
The null-conditional operator short-circuits and its result is nullable.
-
Which operator assigns only when the target is null?
Answer
??=
??= is the null-coalescing assignment: it writes the right side only for a null target.
-
What does this program print?
string? s = null; Console.WriteLine($"x{s?.Length ?? 7}y");Answer
x7y
The ?. gives null, ?? turns it into 7, and the interpolation prints it between the letters.
-
How is a second
fromclause in query syntax compiled?Answer
As SelectMany
A second from reads each item as a sequence, which is exactly SelectMany.
-
Why is
inta dangerous item type for FirstOrDefault?Answer
A miss returns 0, which a real value can also be
Zero is a valid score, so a miss and a zero result cannot be told apart without a nullable type.
-
What does this program print?
var w = new[] { "ab", "cd" }; Console.WriteLine(w.Select(x => x.Length).Sum());Answer
4
The projection gives the two lengths 2 and 2, and Sum adds them.
-
Why does a Select inside a Select not flatten the result?
Answer
Select gives one output item per input item, and that item is a sequence
Only SelectMany concatenates the inner sequences; Select keeps the nesting and prints the inner objects.
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