Bird
Raised Fist0
C Sharp (C#)programming~10 mins

First, Single, and their OrDefault variants in C Sharp (C#) - Step-by-Step Execution

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Concept Flow - First, Single, and their OrDefault variants
Start with a collection
Check if collection is empty?
Return default
Throw exception
This flow shows how First and Single methods check the collection: if empty, return default or throw; if multiple matches for Single, throw; otherwise return the element.
Execution Sample
C Sharp (C#)
var numbers = new[] {1, 2, 3};
var first = numbers.First();
var single = numbers.Single(x => x == 2);
var firstOrDefault = numbers.FirstOrDefault(x => x > 3);
var singleOrDefault = numbers.SingleOrDefault(x => x > 3);
This code gets the first element, a single matching element, and uses OrDefault variants to safely handle no matches.
Execution Table
StepMethod CallCondition CheckedResultAction Taken
1First()Collection not emptyTrueReturn first element: 1
2Single(x == 2)Exactly one element matchesTrueReturn element: 2
3FirstOrDefault(x > 3)Any element matches?FalseReturn default: 0
4SingleOrDefault(x > 3)Any element matches?FalseReturn default: 0
5Single(x > 1)More than one element matchesTrueThrow InvalidOperationException
6First()Collection emptyFalseThrow InvalidOperationException
7FirstOrDefault()Collection emptyTrueReturn default: 0
💡 Execution stops when method returns element, default, or throws exception.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3After Step 4
numbers[1, 2, 3][1, 2, 3][1, 2, 3][1, 2, 3][1, 2, 3]
firstundefined1111
singleundefinedundefined222
firstOrDefaultundefinedundefinedundefined00
singleOrDefaultundefinedundefinedundefinedundefined0
Key Moments - 3 Insights
Why does Single throw an exception when more than one element matches?
Single expects exactly one match. If multiple elements match, it throws to signal ambiguity, as shown in step 5 of the execution_table.
What is the difference between First and FirstOrDefault when the collection is empty?
First throws an exception if empty (step 6), while FirstOrDefault returns the default value (step 7), avoiding exceptions.
When does SingleOrDefault return default instead of throwing?
SingleOrDefault returns default if no elements match (step 4), but throws if multiple elements match, unlike FirstOrDefault.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what value does 'firstOrDefault' have after step 3?
A2
B0
C1
DException thrown
💡 Hint
Check the 'Result' and 'Action Taken' columns for step 3 in execution_table.
At which step does Single throw an exception due to multiple matches?
AStep 5
BStep 2
CStep 6
DStep 7
💡 Hint
Look for 'Throw InvalidOperationException' in the 'Action Taken' column.
If the collection was empty, what would First() do according to the execution_table?
AReturn default value
BReturn first element
CThrow InvalidOperationException
DReturn null
💡 Hint
See step 6 where First() is called on an empty collection.
Concept Snapshot
First() returns the first element or throws if empty.
Single() returns the only matching element or throws if none or multiple.
FirstOrDefault() returns first element or default if empty.
SingleOrDefault() returns single matching element or default if none, throws if multiple.
Use OrDefault variants to avoid exceptions on empty or no matches.
Full Transcript
This visual execution shows how First, Single, and their OrDefault variants work in C#. First returns the first element or throws if the collection is empty. Single returns the only matching element or throws if none or more than one match exists. The OrDefault variants return default values instead of throwing exceptions when no elements match or the collection is empty. The execution table traces each method call, conditions checked, and results or exceptions. Variable tracking shows how variables change after each step. Key moments clarify common confusions about exceptions and default returns. The quiz tests understanding of method behaviors at specific steps.

Practice

(1/5)
1.

Which method will throw an exception if the collection does not have exactly one matching element?

First(), FirstOrDefault(), Single(), SingleOrDefault()
easy
A. SingleOrDefault()
B. First()
C. FirstOrDefault()
D. Single()

Solution

  1. Step 1: Understand Single() behavior

    Single() expects exactly one matching element and throws if there are zero or more than one.
  2. Step 2: Compare with other methods

    First() and FirstOrDefault() do not throw if multiple elements exist; SingleOrDefault() throws only if multiple elements exist but returns default if none.
  3. Final Answer:

    Single() -> Option D
  4. Quick Check:

    Throws on multiple matches = Single() [OK]
Hint: Single() throws if more than one match exists [OK]
Common Mistakes:
  • Confusing Single() with First() which returns first match
  • Thinking FirstOrDefault() throws on multiple matches
  • Assuming SingleOrDefault() never throws
2.

Which of the following is the correct syntax to get the first element or default from a list numbers?

var result = numbers._____();
easy
A. Single
B. FirstOrDefault
C. First
D. SingleOrDefault

Solution

  1. Step 1: Identify method for first or default

    FirstOrDefault() returns the first element or default if none found.
  2. Step 2: Check syntax correctness

    numbers.FirstOrDefault() is valid syntax to get first or default.
  3. Final Answer:

    FirstOrDefault -> Option B
  4. Quick Check:

    FirstOrDefault() syntax correct for first or default [OK]
Hint: Use FirstOrDefault() to safely get first or default [OK]
Common Mistakes:
  • Using Single() which throws if multiple elements
  • Using First() which throws if empty
  • Using SingleOrDefault() which expects single element
3.

What will be the output of this code?

var list = new List<int> { 5, 10, 15 };
var result = list.SingleOrDefault(x => x == 10);
Console.WriteLine(result);
medium
A. 10
B. 0
C. Throws exception
D. null

Solution

  1. Step 1: Understand SingleOrDefault with predicate

    SingleOrDefault returns the only element matching predicate or default if none, throws if multiple.
  2. Step 2: Check list and predicate

    List has one element equal to 10, so SingleOrDefault returns 10.
  3. Final Answer:

    10 -> Option A
  4. Quick Check:

    SingleOrDefault returns single matching element = 10 [OK]
Hint: SingleOrDefault returns single match or default, throws if many [OK]
Common Mistakes:
  • Expecting 0 as default when element exists
  • Thinking it throws because of multiple elements in list
  • Confusing with FirstOrDefault behavior
4.

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);
medium
A. Returns "apple" without error
B. Returns null because of duplicates
C. Throws InvalidOperationException due to multiple matches
D. Syntax error in lambda expression

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]
Hint: Single() throws if more than one match found [OK]
Common Mistakes:
  • Expecting Single() to return first match
  • Thinking it returns null on duplicates
  • Assuming syntax error in lambda
5.

You have a list of users and want to get the only user with the username "admin" or null if none exists. Which method should you use to avoid exceptions if there are no or multiple admins?

hard
A. FirstOrDefault()
B. SingleOrDefault() with try-catch
C. Single()
D. First()

Solution

  1. Step 1: Understand requirements

    We want the only user named "admin" or null if none, but avoid exceptions if multiple exist.
  2. Step 2: Evaluate methods

    SingleOrDefault() throws if multiple matches, so risky. FirstOrDefault() returns first or null safely even if multiple exist.
  3. Final Answer:

    FirstOrDefault() -> Option A
  4. Quick Check:

    FirstOrDefault() safely returns first or null without exceptions [OK]
Hint: Use FirstOrDefault() to avoid exceptions on multiple matches [OK]
Common Mistakes:
  • Using SingleOrDefault() which throws on multiple matches
  • Using Single() which throws on zero or multiple matches
  • Using First() which throws if none found