DEV Community

Captain Iminza
Captain Iminza

Posted on

LINQ First and FirstOrDefault Methods in C#

In C#, First() and FirstOrDefault() are two commonly used LINQ extension methods that allow you to query collections, such as arrays, lists, and other IEnumerable types, to retrieve the first element that matches a specified condition. While these methods might seem similar at first glance, they differ in terms of behavior, especially when the collection is empty or when no element matches the condition.

What is First()?
First() is a LINQ method that returns the first element in a collection that satisfies a given condition. If the collection is empty or no element matches the condition, First() throws an exception of type InvalidOperationException.

What is FirstOrDefault()?
FirstOrDefault() is very similar to First(), but with one key difference: it returns a default value when no element matches the condition or if the collection is empty. The default value depends on the type of the element in the collection. For reference types (like classes), the default value is null, and for value types (like integers), it’s the default value for that type (e.g., 0 for int).

When to Use First() and FirstOrDefault()?

  • Use First() when you are sure that the collection will not be empty and that at least one element will satisfy the condition. This method is useful when the absence of elements matching the condition is considered an error in your application.

Example: If you're querying a database and expecting exactly one result, you may use First() to fetch that record.

  • Use FirstOrDefault() when the absence of a matching element is valid and you want to avoid exceptions. This is often used in scenarios where the collection might be empty, or no elements meet the condition, and you want to handle these cases gracefully.

Example: When fetching a user by ID or username, you might use FirstOrDefault() because it’s possible the user might not exist, and you can handle the null result in your code.

Scenario: Searching for an Employee by ID
Imagine we have a list of employees, and we want to search for an employee by their ID. The employee list might be empty, or there may not be any employee with the given ID. We will explore how First() and FirstOrDefault() behave in such a case.

Employee Class:
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
}

List of Employees:
List<Employee> employees = new List<Employee>
{
new Employee { Id = 1, Name = "John Doe" },
new Employee { Id = 2, Name = "Jane Smith" },
new Employee { Id = 3, Name = "Mike Johnson" }
};

Example 1: Using First()
Let’s say we want to find an employee with ID 4. Since there is no employee with that ID in the list, using First() will throw an exception.
try
{
var employee = employees.First(e => e.Id == 4);
Console.WriteLine($"Employee Found: {employee.Name}");
}
catch (InvalidOperationException ex)
{
Console.WriteLine($"Error: {ex.Message}"); // Output: "Sequence contains no elements"
}

In this case, since no employee has an ID of 4, First() throws an InvalidOperationException, indicating that no element matches the condition.

Example 2: Using FirstOrDefault()
Now let’s see how FirstOrDefault() behaves when trying to find an employee with ID 4.

var employee = employees.FirstOrDefault(e => e.Id == 4);

if (employee != null)
{
    Console.WriteLine($"Employee Found: {employee.Name}");
}
else
{
    Console.WriteLine("No employee found with ID 4");  // Output: "No employee found with ID 4"
}
Enter fullscreen mode Exit fullscreen mode

In this example, FirstOrDefault() returns null because no employee with ID 4 exists in the list. Instead of throwing an exception, we can handle the case gracefully by checking if employee is null and displaying a message to the user.

Example 3: Empty List Scenario
Let’s consider a situation where the employee list is empty:

List<Employee> emptyList = new List<Employee>();

try
{
    var employee = emptyList.First(e => e.Id == 1);  // This will throw an exception
    Console.WriteLine($"Employee Found: {employee.Name}");
}
catch (InvalidOperationException ex)
{
    Console.WriteLine($"Error: {ex.Message}");  // Output: "Sequence contains no elements"
}
Enter fullscreen mode Exit fullscreen mode

Now, let’s use FirstOrDefault() with the same empty list:

var employee = emptyList.FirstOrDefault(e => e.Id == 1);

if (employee != null)
{
    Console.WriteLine($"Employee Found: {employee.Name}");
}
else
{
    Console.WriteLine("No employee found");  // Output: "No employee found"
}
Enter fullscreen mode Exit fullscreen mode

Key Takeaways

  • First() will throw an exception if the collection is empty or if no element satisfies the condition. This is useful when you want to ensure that the element must exist.

  • FirstOrDefault() will return the default value (null for reference types) if no element matches or if the collection is empty. This allows for safer handling when the absence of a matching element is expected or valid.

By using FirstOrDefault() in scenarios where the absence of an element is acceptable, you can avoid potential crashes in your application due to unhandled exceptions.

By understanding these differences, you can write more predictable and error-resistant code, especially when working with dynamic or uncertain data sources.

Happy coding!

Top comments (0)