0
0
CsharpHow-ToBeginner · 4 min read

How to Use LINQ First and FirstOrDefault in C#

In C#, First returns the first element of a sequence and throws an exception if none exists, while FirstOrDefault returns the first element or a default value (like null) if the sequence is empty. Use First when you expect at least one item, and FirstOrDefault when the sequence might be empty and you want to avoid exceptions.
📐

Syntax

First and FirstOrDefault are LINQ methods used to get the first element from a collection.

  • First(): Returns the first element or throws InvalidOperationException if empty.
  • FirstOrDefault(): Returns the first element or default value (like null for reference types) if empty.
  • Both can take an optional predicate (item => condition) to find the first element matching a condition.
csharp
var firstItem = collection.First();
var firstOrDefaultItem = collection.FirstOrDefault();
var firstMatch = collection.First(item => item.Property == value);
var firstOrDefaultMatch = collection.FirstOrDefault(item => item.Property == value);
💻

Example

This example shows how to use First and FirstOrDefault to get elements from a list of numbers and handle empty sequences safely.

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

class Program
{
    static void Main()
    {
        List<int> numbers = new List<int> { 10, 20, 30, 40 };
        
        // First returns the first element
        int firstNumber = numbers.First();
        Console.WriteLine($"First number: {firstNumber}");

        // FirstOrDefault returns the first element or 0 if empty
        int firstOrDefaultNumber = numbers.FirstOrDefault();
        Console.WriteLine($"FirstOrDefault number: {firstOrDefaultNumber}");

        // Using predicate to find first number greater than 25
        int firstGreaterThan25 = numbers.First(n => n > 25);
        Console.WriteLine($"First number > 25: {firstGreaterThan25}");

        // Empty list example
        List<int> emptyList = new List<int>();

        // This will throw InvalidOperationException
        // int fail = emptyList.First();

        // This returns default(int) which is 0
        int safe = emptyList.FirstOrDefault();
        Console.WriteLine($"FirstOrDefault on empty list: {safe}");
    }
}
Output
First number: 10 FirstOrDefault number: 10 First number > 25: 30 FirstOrDefault on empty list: 0
⚠️

Common Pitfalls

Using First on an empty collection throws an exception. This can crash your program if not handled.

Using FirstOrDefault returns a default value, which might be null or zero, so always check the result before using it.

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

class PitfallExample
{
    static void Main()
    {
        List<string> names = new List<string>();

        // Wrong: This throws exception if list is empty
        // string firstName = names.First();

        // Right: Use FirstOrDefault and check for null
        string safeName = names.FirstOrDefault();
        if (safeName == null)
        {
            Console.WriteLine("No names found.");
        }
        else
        {
            Console.WriteLine($"First name: {safeName}");
        }
    }
}
Output
No names found.
📊

Quick Reference

MethodBehaviorThrows Exception?Returns Default Value?
First()Returns first elementYes, if emptyNo
FirstOrDefault()Returns first element or defaultNoYes (null, 0, etc.)
First(predicate)Returns first element matching conditionYes, if none matchNo
FirstOrDefault(predicate)Returns first element matching condition or defaultNoYes

Key Takeaways

Use First() when you are sure the collection has at least one matching element.
Use FirstOrDefault() to safely get the first element or a default value if none exists.
Always check the result of FirstOrDefault() for default values before using it.
First and FirstOrDefault can take a condition to find the first matching element.
Avoid calling First() on empty collections to prevent exceptions.