NashTech Blog

LINQ First and FirstOrDefault Methods in C# Explained

Table of Contents
ai generated, body, ghost-8404948.jpg

LINQ provides two methods, First() and FirstOrDefault(), that are used to retrieve the first element from a sequence. While they may seem similar, they have subtle differences that are important to understand. In this article, we will explore these methods, their differences, and provide examples to demonstrate their usage.

What are First() and FirstOrDefault() Methods in LINQ?

  • First(): This method returns the first element of a sequence that satisfies a specified condition. If no such element is found, then it throws an exception.
  • FirstOrDefault(): This method returns the first element of a sequence that satisfies a specified condition, or a default value if no such element is found. The default value for reference types is null, and for value types, it’s the default value of the type (e.g., 0 for int).

 

Usage Examples
Let’s consider a simple example to understand the usage of these methods:

using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
static void Main()
{
var numbers = new List<int> { 1, 2, 3, 4, 5 };

// First
int first = numbers.First();
Console.WriteLine($"First: {first}"); // Output: First: 1

// FirstOrDefault
int? firstOrDefault = numbers.FirstOrDefault(x => x > 5);
Console.WriteLine($"FirstOrDefault: {firstOrDefault}"); // Output: FirstOrDefault: null
}
}

In this example, we have a list of numbers, and we use First() to retrieve the first element (1) and FirstOrDefault() to retrieve the first element greater than 5 (which doesn’t exist, so it returns null).

 

Real-Life Example

Imagine you have a collection of students and you want to find the first student whose name starts with ‘A’:

using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
static void Main()
{
var students = new List<string> { "Alice", "Bob", "Charlie", "Eve" };

string firstStudentWithA = students.FirstOrDefault(s => s.StartsWith("A"));
Console.WriteLine($"First student with name starting with 'A': {firstStudentWithA}");
}
}

In this example, FirstOrDefault() is used to find the first student whose name starts with ‘A’.

 

Difference Between First() and FirstOrDefault()

The key difference between First() and FirstOrDefault() lies in how they handle empty sequences:

  • First(): If the sequence is empty or if no element satisfies the condition, First() will throw an InvalidOperationException.
  • FirstOrDefault(): If the sequence is empty or if no element satisfies the condition, FirstOrDefault() will return the default value for the type.

 

Conclusion

In summary, First() and FirstOrDefault() are useful methods in LINQ for retrieving the first element of a sequence. First() should be used when you expect the sequence to contain at least one element that satisfies the condition, while FirstOrDefault() should be used when you are unsure if the sequence will contain any elements or if it’s acceptable to return a default value if no element is found. Understanding these methods and their differences will help you use them effectively in your C# code.

Picture of sujitmeshram

sujitmeshram

Leave a Comment

Your email address will not be published. Required fields are marked *

Suggested Article

Scroll to Top