Challenge - 5 Problems
SelectMany Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
What is the output of this SelectMany example?
Consider the following C# code using LINQ's SelectMany method. What will be printed to the console?
C Sharp (C#)
var numbers = new List<List<int>> { new List<int> {1, 2}, new List<int> {3, 4}, new List<int> {5} }; var flat = numbers.SelectMany(x => x); foreach(var num in flat) { Console.Write(num + " "); }
Attempts:
2 left
💡 Hint
SelectMany flattens nested collections into one sequence.
✗ Incorrect
SelectMany takes each inner list and combines all elements into a single sequence. So all numbers from all inner lists are printed in order.
❓ Predict Output
intermediate2:00remaining
What does this SelectMany with index produce?
Look at this C# code using SelectMany with an index parameter. What is the output?
C Sharp (C#)
var data = new List<string[]> { new string[] {"a", "b"}, new string[] {"c"}, new string[] {"d", "e", "f"} }; var result = data.SelectMany((arr, i) => arr.Select(s => s + i)); foreach(var s in result) { Console.Write(s + " "); }
Attempts:
2 left
💡 Hint
The index i is the position of the outer array in the list.
✗ Incorrect
SelectMany passes the index of each inner array. Each string is concatenated with that index, so first array elements get '0', second '1', third '2'.
🔧 Debug
advanced2:00remaining
Why does this SelectMany code throw an exception?
This code throws an exception at runtime. What is the cause?
C Sharp (C#)
var list = new List<List<int>> { new List<int> {1, 2}, null, new List<int> {3} }; var flat = list.SelectMany(x => x); foreach(var n in flat) { Console.Write(n + " "); }
Attempts:
2 left
💡 Hint
Check what happens when SelectMany tries to iterate a null collection.
✗ Incorrect
SelectMany tries to iterate each inner list. When it reaches the null element, it throws NullReferenceException because you cannot iterate null.
📝 Syntax
advanced2:00remaining
Which option correctly uses SelectMany to flatten and filter?
You want to flatten a list of integer arrays and keep only even numbers. Which code snippet does this correctly?
Attempts:
2 left
💡 Hint
Use Where inside SelectMany to filter elements.
✗ Incorrect
Option B correctly uses Where to filter even numbers inside each inner collection before flattening. Others have syntax errors or wrong methods.
🚀 Application
expert2:00remaining
How many items are in the flattened list?
Given this nested list, how many integers will be in the flattened list after using SelectMany?
C Sharp (C#)
var nested = new List<List<int>> { new List<int> {1, 2, 3}, new List<int> {}, new List<int> {4, 5}, new List<int> {6} }; var flat = nested.SelectMany(x => x).ToList(); int count = flat.Count;
Attempts:
2 left
💡 Hint
Count all elements in all inner lists combined.
✗ Incorrect
The inner lists have 3 + 0 + 2 + 1 elements = 6 total elements after flattening.