Bird
0
0

How do you correctly retrieve the first element or a default value from a list called items in C#?

easy📝 Syntax Q3 of 15
C Sharp (C#) - LINQ Fundamentals

How do you correctly retrieve the first element or a default value from a list called items in C#?

Avar result = items.Single();
Bvar result = items.FirstOrDefault();
Cvar result = items.Last();
Dvar result = items.SingleOrDefault();
Step-by-Step Solution
Solution:
  1. Step 1: Understand the method purpose

    FirstOrDefault() returns the first element or default if none exists.
  2. Step 2: Check alternatives

    Single() expects exactly one element, Last() returns last element, SingleOrDefault() expects zero or one element.
  3. Final Answer:

    var result = items.FirstOrDefault(); -> Option B
  4. Quick Check:

    First element or default [OK]
Quick Trick: Use FirstOrDefault() to safely get first or default [OK]
Common Mistakes:
MISTAKES
  • Using Single() when multiple elements exist
  • Using Last() instead of FirstOrDefault()
  • Confusing SingleOrDefault() with FirstOrDefault()

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More C Sharp (C#) Quizzes