LINQ
.First
.FirstOrDefault
Programming
C#

When to use .First and when to use .FirstOrDefault with LINQ?

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

When working with LINQ (Language Integrated Query) in .NET, developers often encounter scenarios where they need to retrieve an element from a sequence. Two commonly used methods for this purpose are .First() and .FirstOrDefault(). Understanding when to use each method is crucial for writing correct, efficient, and bug-free code. Here, we will explore both methods, their differences, and the appropriate contexts to use them.

Understanding .First()

The .First() method is used to return the first element in a sequence. If the sequence contains no elements, .First() will throw an InvalidOperationException. This method is suitable when you are confident that the collection is not empty.

Example Usage:

csharp
List<int> numbers = new List<int> { 1, 2, 3 };
int firstNumber = numbers.First();
Console.WriteLine(firstNumber); // Output: 1

However, if you use .First() on an empty list:

csharp
List<int> emptyNumbers = new List<int>();
int firstNumber = emptyNumbers.First(); // This will throw InvalidOperationException

Understanding .FirstOrDefault()

The .FirstOrDefault() method functions similarly to .First(), but with a crucial difference: if the sequence is empty, it returns the default value for the type. For reference types, the default is null, and for value types, the default is typically zero or a struct initialized to zero for each member.

Example Usage:

csharp
1List<int> numbers = new List<int> { 1, 2, 3 };
2int firstNumber = numbers.FirstOrDefault();  // Output: 1
3
4List<int> emptyNumbers = new List<int>();
5int firstOrDefaultNumber = emptyNumbers.FirstOrDefault(); // Output: 0 (default int value)

This method is highly beneficial when dealing with possible empty collections as it helps avoid exceptions.

Technical Comparison and Use Cases

MethodReturns if not emptyReturns if emptyThrows ExceptionSuitable Use Case
.First()First elementN/AYesWhen the collection is guaranteed to have elements.
.FirstOrDefault()First elementDefault value of typeNoWhen the collection could be empty.
  • Use .First() when:
    • You are certain the collection will not be empty.
    • An empty collection is considered an exceptional error in logic.
  • Use .FirstOrDefault() when:
    • The collection might be empty, and handling a null or default value is part of the normal flow.
    • You want to avoid the overhead of exception handling which would be required with .First().

Practical Considerations

Querying Databases

When querying data from a database, using .FirstOrDefault() can be more common, as often, you do not know if the result set will contain any rows until runtime.

Performance Implications

Both methods perform similarly in terms of speed; however, .First() could be slightly faster in scenarios where it is known that the collection will never be empty since there's no need to check for an empty collection before returning the element.

Error Handling

Using .FirstOrDefault() allows for smoother error handling. By checking if the result is the default value rather than catching an exception, you can make your code cleaner and more readable.

Conclusion

Choosing between .First() and .FirstOrDefault() mainly depends on your certainty about the content of the sequence and how you wish to handle cases where the sequence might be empty. Correctly picking between these two methods can lead to more robust and understandable code. Always consider the context of your data and the operational requirements before deciding which method to use.


Related reading
Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.