When to use .First and when to use .FirstOrDefault with LINQ?
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Using LINQ, or Language Integrated Query, to manipulate collections and return specific items from datasets is common in .NET development. Two methods often used for retrieving the first element in a sequence are .First() and .FirstOrDefault(). Understanding when and why to use each method is crucial to prevent runtime errors and ensure the code behaves as expected.
Technical Explanation
.First()
The .First() method is utilized when you are certain that a collection contains at least one element. It throws an InvalidOperationException if the source sequence is empty. Therefore, it's suitable when you have validations or preconditions in your code that ensure that the collection will not be empty at runtime.
Example:
If numbers were an empty list, the code would throw an exception.
.FirstOrDefault()
In contrast, .FirstOrDefault() returns the first element of a collection, or a default value if the sequence contains no elements. For reference types, this default is null, while for value types like int or struct, the default is 0 or the default initialized value.
This method is preferred when the collection might be empty and you need a safe operation to handle such cases elegantly.
Example:
Potential Pitfalls
- Null Checks with
.FirstOrDefault(): Since.FirstOrDefault()can returnnull, it is crucial to include null checks in your logic when working with collections of reference types. - Incorrect Assumptions with
.First(): Using.First()when you assume the collection cannot be empty might lead to unhandled exceptions if the collection state changes over time (e.g., after certain operations like filtering).
Advantages and Use Cases
.First()
- Performance: Slightly faster than
.FirstOrDefault()because it does not involve checking for a default value. - Assumption: Use when the collection is guaranteed to be non-empty due to prior logic validations or constraints.
.FirstOrDefault()
- Safety: Avoids exceptions when dealing with potentially empty collections, making it a more defensive approach.
- Nullability: Suitable for scenarios where the absence of elements should be handled gracefully without disrupting the flow, such as in user search queries or potentially empty lists.
Scenarios and Best Practices
- Data Retrieval in APIs:
- When fetching a list from a database or external service where the list could be empty, prefer
.FirstOrDefault(). - Example: Retrieving user details by ID that may or may not exist.
- Pre-validated Data Sources:
- If the data source is pre-validated or guarantees at least one item (like settings arrays),
.First()can be used. - Example: Accessing the first element of configuration items loaded during application startup.
- Functional Composition:
- Integrate null-coalescing operators for
.FirstOrDefault()results to ensure safe subsequent operations. - Example:
var firstName = users.FirstOrDefault()?.Name ?? "No Name";
Key Point Summary
| Method | Description | When to Use | Return Value |
.First() | Returns the first element of a sequence. | Use when the collection is guaranteed to be non-empty. | First element or throws exception |
.FirstOrDefault() | Returns the first element or a default value if empty. | Use when the collection might be empty and need to handle safely. | First element or default (null or 0) |
In summary, choose .First() when collection non-emptiness is assured, providing slightly better performance. Opt for .FirstOrDefault() for potentially empty collections, enhancing stability and reducing exceptions in your code.

