Recall & Review
beginner
What does the
First() method do in C#?It returns the first element of a sequence. If the sequence is empty, it throws an exception.
Click to reveal answer
beginner
How does
FirstOrDefault() differ from First()?FirstOrDefault() returns the first element if found; otherwise, it returns the default value for the type (e.g., null for reference types, 0 for integers) instead of throwing an exception.Click to reveal answer
intermediate
What is the key difference between
Single() and First()?Single() expects exactly one element in the sequence and throws an exception if there are zero or more than one elements. First() only requires at least one element and returns the first one.Click to reveal answer
intermediate
When should you use
SingleOrDefault()?Use
SingleOrDefault() when you expect zero or one element in the sequence. It returns the single element if found, or the default value if none are found. It throws an exception if more than one element exists.Click to reveal answer
beginner
What happens if you call
Single() on a sequence with multiple elements?It throws an
InvalidOperationException because Single() expects exactly one element, not multiple.Click to reveal answer
What does
FirstOrDefault() return if the sequence is empty?✗ Incorrect
FirstOrDefault() returns the default value for the type if the sequence is empty, such as null for reference types or 0 for integers.Which method throws an exception if the sequence contains more than one element?
✗ Incorrect
Single() throws an exception if there is more than one element in the sequence.If you want to get the first element but avoid exceptions on empty sequences, which method should you use?
✗ Incorrect
FirstOrDefault() safely returns the first element or a default value if the sequence is empty.What will
SingleOrDefault() return if the sequence has exactly one element?✗ Incorrect
SingleOrDefault() returns the single element if exactly one exists.Which method is best when you expect exactly one element and want an exception if zero or multiple elements exist?
✗ Incorrect
Single() enforces exactly one element and throws if zero or more than one exist.Explain the difference between
First() and Single() methods in C#.Think about how many elements each method expects and what happens if the sequence is empty or has many elements.
You got /4 concepts.
When would you choose to use
FirstOrDefault() or SingleOrDefault()?Consider the expected number of elements and how you want to handle empty sequences.
You got /4 concepts.