Extracting a Single Element
LINQ provides several operators for pulling exactly one element out of a sequence, and choosing the wrong one either masks bugs or crashes your program at the wrong moment. First() returns the first element and throws if the sequence is empty; FirstOrDefault() returns default(T) (often null or 0) instead of throwing. These stop enumerating as soon as a match is found, making them efficient even on very large or infinite sequences.
Cricket analogy: Asking 'who's the first batter in today's lineup' just checks the opening slot and stops, exactly like First() returning immediately after the first element without scanning the rest of the batting order.
First vs FirstOrDefault vs Single
Single() is stricter than First(): it throws InvalidOperationException not only when the sequence is empty but also when it contains more than one matching element, because Single() asserts uniqueness, not just presence. SingleOrDefault() relaxes the empty case (returns default(T) instead of throwing) but still throws if there's more than one match — it's the right choice when you're looking up by a unique key like a primary key or username and want a hard failure if your uniqueness assumption is ever violated.
Cricket analogy: Looking up 'the player named Virat Kohli' in a squad list should match exactly one person, and Single() throws if a data glitch duplicated the entry, just as it enforces there's only one qualifying element.
ElementAt and ElementAtOrDefault
ElementAt(index) retrieves the element at a specific zero-based position; for an IList<T> it's an O(1) indexed lookup, but for a plain IEnumerable<T> (like the result of a Where() chain) it must walk the sequence from the start, making it O(n) — so calling ElementAt() repeatedly in a loop over a non-indexed source is a common performance trap. ElementAtOrDefault(index) returns default(T) instead of throwing ArgumentOutOfRangeException when the index is out of bounds, which is useful for safely peeking at a position that might not exist, such as 'the third search result if there is one'.
Cricket analogy: Jumping straight to over 37, ball 4 in a stored scorecard array is instant, but replaying a live radio commentary stream from the start to reach that exact ball is slow, mirroring how ElementAt() is O(1) on an IList<T> but O(n) on a plain IEnumerable<T>.
var users = new List<User>
{
new User { Id = 1, Email = "a@example.com" },
new User { Id = 2, Email = "b@example.com" },
};
// First throws InvalidOperationException if empty
var firstUser = users.First();
// FirstOrDefault returns null instead of throwing
var maybeAdmin = users.FirstOrDefault(u => u.Email == "admin@example.com");
// Single enforces uniqueness — throws if 0 or >1 matches
var byId = users.Single(u => u.Id == 2);
// SingleOrDefault: null if none found, still throws if duplicates exist
var maybeById = users.SingleOrDefault(u => u.Id == 99); // null
// ElementAt is O(1) here because List<T> implements IList<T>
var second = users.ElementAt(1);
// Safe peek at a position that might not exist
var third = users.ElementAtOrDefault(2); // null, no exceptionSingle() is not just 'like First() but pickier' — it actively validates that exactly one element matches. Using Single() where First() was intended (e.g., 'get the most recent order') will throw the moment there are two orders, even though First() combined with OrderByDescending() would have worked fine.
All six operators — First, FirstOrDefault, Single, SingleOrDefault, Last, LastOrDefault — accept an optional predicate, e.g. First(u => u.IsActive), so you rarely need to chain Where() before them; passing the predicate directly is more idiomatic and equally efficient.
- First() and FirstOrDefault() stop enumerating as soon as a match is found — both are efficient even on large sequences.
- First() throws on an empty sequence; FirstOrDefault() returns default(T) instead.
- Single() throws if there are zero OR more than one matching elements — it asserts uniqueness.
- SingleOrDefault() tolerates zero matches (returns default) but still throws on duplicates.
- ElementAt() is O(1) on IList<T> sources but O(n) on plain IEnumerable<T> sources.
- ElementAtOrDefault() avoids ArgumentOutOfRangeException for out-of-range indexes.
- Prefer passing a predicate directly to First/Single rather than chaining Where() first.
Practice what you learned
1. What exception does First() throw when the source sequence is empty?
2. When does Single() throw an exception?
3. What is the time complexity of ElementAt(5) on a plain IEnumerable<T> produced by a Where() clause?
4. Which method is best for 'look up a user by unique email, and it's fine if no such user exists'?
5. What does ElementAtOrDefault(10) return if the sequence only has 3 elements?
Was this page helpful?
You May Also Like
Aggregate Functions: Sum, Count, Average
Learn how LINQ's Sum, Count, and Average operators collapse sequences into single scalar values, and how execution timing and edge cases affect their use.
Any, All, and Contains
Master LINQ's boolean-returning quantifier operators — Any, All, and Contains — and how their short-circuiting behavior makes them efficient existence checks.
Set Operations: Union, Intersect, Except
Learn how LINQ's set operators — Union, Intersect, Except, and Distinct — deduplicate and compare sequences using equality semantics.
Related Reading
Related Study Notes in Microsoft Technologies
Browse all study notesWindows 10 / UWP Development Study Notes
.NET · 30 topics
Microsoft TechnologiesWindows Batch Scripting Study Notes
Batch · 30 topics
Microsoft TechnologiesMFC (Microsoft Foundation Classes) Study Notes
C++ · 30 topics
Microsoft TechnologiesSilverlight Study Notes
.NET · 30 topics
Microsoft TechnologiesXAML Study Notes
.NET · 30 topics
Microsoft TechnologiesWPF (Windows Presentation Foundation) Study Notes
.NET · 30 topics