.NET API Documentation

Home > .NET API > System.Linq > FirstOrDefault

FirstOrDefault Method

public static TSource FirstOrDefault<TSource>(this IEnumerable<TSource> source);
public static TSource FirstOrDefault<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate);

Description

Returns the first element of a sequence that satisfies a condition, or a default value if no such element is found.

Overload List

Parameters

Returns

The first element of the sequence that satisfies the condition, or the default value for the type of the elements in the sequence if no such element is found.

Exceptions

Remarks

If the type of elements in source is a reference type, the default value is null. If the type of elements is a value type, the default value is the value returned by calling the parameterless constructor of the value type (e.g., 0 for numeric types, false for bool, and null for nullable value types).

The FirstOrDefault method enumerates through the sequence and stops as soon as it finds an element that satisfies the condition. If the sequence is empty or no element satisfies the condition, it returns the default value for the element type.

Example

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

public class Example
{
    public static void Main(string[] args)
    {
        List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };

        // Get the first element, or 0 if the list is empty
        int firstOrDefaultValue = numbers.FirstOrDefault();
        Console.WriteLine($ "FirstOrDefault without predicate: {firstOrDefaultValue}"); // Output: 1

        // Get the first element greater than 3, or 0 if none found
        int firstGreaterThanThree = numbers.FirstOrDefault(n => n > 3);
        Console.WriteLine($ "FirstOrDefault with predicate (n > 3): {firstGreaterThanThree}"); // Output: 4

        List<int> emptyList = new List<int>();
        int firstInEmpty = emptyList.FirstOrDefault();
        Console.WriteLine($ "FirstOrDefault on empty list: {firstInEmpty}"); // Output: 0

        int firstGreaterThanTen = numbers.FirstOrDefault(n => n > 10);
        Console.WriteLine($ "FirstOrDefault with predicate (n > 10): {firstGreaterThanTen}"); // Output: 0

        List<string> names = new List<string> { "Alice", "Bob", "Charlie" };
        string firstDefaultName = names.FirstOrDefault();
        Console.WriteLine($ "FirstOrDefault on string list: {firstDefaultName}"); // Output: Alice

        string firstDefaultNullName = null;
        List<string> nullNames = new List<string>();
        string firstInNullNames = nullNames.FirstOrDefault();
        Console.WriteLine($ "FirstOrDefault on null string list: {firstInNullNames ?? "null"}"); // Output: null
    }
}

See Also