System.Linq.Enumerable.First

public static TSource First<TSource>(IEnumerable<TSource> source)

Summary

Returns the first element of a sequence.

Syntax

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

Parameters

Name Description Type
source An IEnumerable<TSource> to return the first element of. IEnumerable<TSource>
predicate A function to test each element for a condition. Func<TSource, bool>

Returns

Type Description
TSource The first element of the specified sequence.

Exceptions

Type Description
ArgumentNullException source is null.
InvalidOperationException The sequence contains no elements.
ArgumentNullException predicate is null.
InvalidOperationException No element satisfies the condition in predicate.

Examples

The following code example demonstrates how to use the First method to retrieve the first element of an array and the first element that satisfies a condition.

Example 1: Get the first element of an array

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

public class Example
{
    public static void Main(string[] args)
    {
        int[] numbers = { 5, 4, 3, 2, 1 };
        int firstNumber = numbers.First(); // firstNumber will be 5

        Console.WriteLine($"The first number is: {firstNumber}");
    }
}

Example 2: Get the first element satisfying a condition

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

public class Example
{
    public static void Main(string[] args)
    {
        string[] words = { "apple", "banana", "cherry", "date", "elderberry" };

        // Get the first word that starts with 'c'
        string wordStartingWithC = words.First(w => w.StartsWith("c")); // wordStartingWithC will be "cherry"

        Console.WriteLine($"The first word starting with 'c' is: {wordStartingWithC}");
    }
}

Remarks

The First method iterates through the sequence and returns the first element. If the sequence is empty, it throws an InvalidOperationException. The overload that takes a predicate returns the first element that satisfies the specified condition. If no element satisfies the condition, it also throws an InvalidOperationException.

Note: If you need to retrieve the first element and wish to handle the case where the sequence might be empty without throwing an exception, consider using the FirstOrDefault method instead.