0
0
C Sharp (C#)programming~20 mins

First, Single, and their OrDefault variants in C Sharp (C#) - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
LINQ Mastery: First and Single
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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}");
    }
}
A2 2
B0 0
C2 0
DCompilation error
Attempts:
2 left
💡 Hint
First() returns the first element; FirstOrDefault() returns first or default if none.
Predict Output
intermediate
2: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);
    }
}
ACompilation error
BInvalidOperationException
C0
D2
Attempts:
2 left
💡 Hint
Single() expects exactly one matching element.
Predict Output
advanced
2: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);
    }
}
A2
BInvalidOperationException
CCompilation error
D0
Attempts:
2 left
💡 Hint
SingleOrDefault returns default if no element matches.
Predict Output
advanced
2: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);
    }
}
A5 InvalidOperationException
B5 0
CCompilation error
D5 5
Attempts:
2 left
💡 Hint
SingleOrDefault throws if more than one match exists.
🧠 Conceptual
expert
2:00remaining
Choosing between First() and Single() in LINQ queries
Which statement is TRUE about using First() and Single() in C# LINQ queries?
ASingle() returns the first matching element without checking for others.
BFirst() throws an exception if more than one element matches the condition.
CSingle() throws an exception if zero or more than one element matches the condition.
DFirst() returns default value if no elements match the condition.
Attempts:
2 left
💡 Hint
Think about how Single() enforces uniqueness.