Challenge - 5 Problems
LINQ Mastery: First and Single
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of First() vs FirstOrDefault()
What is the output of the following C# code?
C Sharp (C#)
using System; using System.Linq; class Program { static void Main() { int[] numbers = { 2, 4, 6, 8 }; int first = numbers.First(); int firstOrDefault = numbers.FirstOrDefault(); Console.WriteLine($"{first} {firstOrDefault}"); } }
Attempts:
2 left
💡 Hint
First() returns the first element; FirstOrDefault() returns first or default if none.
✗ Incorrect
The array has elements, so First() returns 2, and FirstOrDefault() also returns 2 because the first element exists.
❓ Predict Output
intermediate2:00remaining
Behavior of Single() with multiple matches
What happens when you run this C# code?
C Sharp (C#)
using System; using System.Linq; class Program { static void Main() { int[] numbers = { 1, 2, 2, 3 }; int single = numbers.Single(x => x == 2); Console.WriteLine(single); } }
Attempts:
2 left
💡 Hint
Single() expects exactly one matching element.
✗ Incorrect
Since there are two elements equal to 2, Single() throws InvalidOperationException due to multiple matches.
❓ Predict Output
advanced2:00remaining
Output of SingleOrDefault() with no matches
What is the output of this C# program?
C Sharp (C#)
using System; using System.Linq; class Program { static void Main() { int[] numbers = { 1, 3, 5 }; int result = numbers.SingleOrDefault(x => x == 2); Console.WriteLine(result); } }
Attempts:
2 left
💡 Hint
SingleOrDefault returns default if no element matches.
✗ Incorrect
No element equals 2, so SingleOrDefault returns default(int) which is 0.
❓ Predict Output
advanced2:00remaining
Difference between FirstOrDefault() and SingleOrDefault() with multiple matches
What is the output of this C# code?
C Sharp (C#)
using System; using System.Linq; class Program { static void Main() { int[] numbers = { 5, 5, 5 }; int firstOrDefault = numbers.FirstOrDefault(x => x == 5); Console.WriteLine(firstOrDefault); int singleOrDefault = numbers.SingleOrDefault(x => x == 5); } }
Attempts:
2 left
💡 Hint
SingleOrDefault throws if more than one match exists.
✗ Incorrect
FirstOrDefault returns the first matching element (5). SingleOrDefault throws InvalidOperationException because multiple matches exist.
🧠 Conceptual
expert2:00remaining
Choosing between First() and Single() in LINQ queries
Which statement is TRUE about using First() and Single() in C# LINQ queries?
Attempts:
2 left
💡 Hint
Think about how Single() enforces uniqueness.
✗ Incorrect
Single() expects exactly one matching element; it throws if none or multiple matches are found. First() throws only if no elements match.