System.Linq
LastOrDefault<TSource>(IEnumerable<TSource>)
Summary
Returns the last element of a sequence, or a default value if the sequence contains no elements.
Syntax
public static TSource LastOrDefault<TSource>(IEnumerable<TSource> source)
Parameters:
- source: IEnumerable<TSource>
An IEnumerable<TSource> to return the last element of.
Returns
TSource
The last element of the sequence, or the default value for type TSource if the sequence is empty.
The last element of the sequence, or the default value for type TSource if the sequence is empty.
Remarks
If the type of TSource is a reference type, this method returns null
if the sequence is empty.
If the type of TSource is a value type, this method returns the default value for that value type (e.g., 0
for int
, false
for bool
) if the sequence is empty.
This method uses deferred execution.
Examples
Example 1: Basic usage
using System;
using System.Collections.Generic;
using System.Linq;
public class Example
{
public static void Main()
{
List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
int lastElement = numbers.LastOrDefault();
Console.WriteLine($"Last element: {lastElement}"); // Output: Last element: 5
List<string> names = new List<string>();
string lastName = names.LastOrDefault();
Console.WriteLine($"Last name: {lastName ?? "null"}"); // Output: Last name: null
List<int?> nullableNumbers = new List<int?>();
int? lastNullableNumber = nullableNumbers.LastOrDefault();
Console.WriteLine($"Last nullable number: {lastNullableNumber?.ToString() ?? "null"}"); // Output: Last nullable number: null
}
}
Example 2: Using with an empty array
using System;
using System.Linq;
public class Example
{
public static void Main()
{
int[] emptyArray = new int[0];
int defaultValue = emptyArray.LastOrDefault();
Console.WriteLine($"Default value for empty int array: {defaultValue}"); // Output: Default value for empty int array: 0
}
}