Bird
0
0

Identify the error in this code snippet:

medium📝 Debug Q14 of 15
C Sharp (C#) - LINQ Fundamentals

Identify the error in this code snippet:

var items = new List<string> { "apple", "banana", "apple" };
var singleItem = items.Single(x => x == "apple");
Console.WriteLine(singleItem);
AReturns "apple" without error
BReturns null because of duplicates
CThrows InvalidOperationException due to multiple matches
DSyntax error in lambda expression
Step-by-Step Solution
Solution:
  1. Step 1: Analyze Single() with multiple matches

    Single() throws InvalidOperationException if more than one element matches the predicate.
  2. Step 2: Check list contents

    List has two "apple" strings, so Single() throws exception.
  3. Final Answer:

    Throws InvalidOperationException due to multiple matches -> Option C
  4. Quick Check:

    Single() throws on multiple matches [OK]
Quick Trick: Single() throws if more than one match found [OK]
Common Mistakes:
MISTAKES
  • Expecting Single() to return first match
  • Thinking it returns null on duplicates
  • Assuming syntax error in lambda

Want More Practice?

15+ quiz questions · All difficulty levels · Free

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