System.Linq.Last

Method: Last<TSource>

Returns the last element of a sequence.

Declaration

public static TSource Last<TSource>(this IEnumerable<TSource> source);

Parameters

source
An IEnumerable<TSource> to return the last element from. This parameter is required.

Return Value

TSource
The last element of the sequence.

Exceptions

ArgumentNullException
source is null.
InvalidOperationException
The sequence is empty.

Remarks

The Last method returns the last element of a sequence. This method is an implementation of the IQueryable<T> Last extension method. For IEnumerable<T> sources, the last element is returned. If the sequence is empty, an InvalidOperationException is thrown.

This method iterates through the sequence. If the sequence is a list or an array, the last element can be accessed more efficiently by using the indexer.

Examples

Example 1: Getting the last element of an array

int[] numbers = { 5, 4, 3, 2, 1 };
int lastNumber = numbers.Last(); // lastNumber is 1

Console.WriteLine(lastNumber);

Example 2: Getting the last element of a list

List<string> names = new List<string> { "Alice", "Bob", "Charlie" };
string lastName = names.Last(); // lastName is "Charlie"

Console.WriteLine(lastName);

Example 3: Handling an empty sequence

List<int> emptyList = new List<int>();
try
{
    int element = emptyList.Last();
}
catch (InvalidOperationException ex)
{
    Console.WriteLine("The sequence is empty.");
    // Output: The sequence is empty.
}

Related Topics