Returns the element at a specified index in a sequence or a default value if the index is out of range.
ElementAtOrDefault(IEnumerable<TSource> source, int index)
ElementAtOrDefault(IEnumerable<TSource> source, int index, TSource defaultValue)
Returns the element at the specified position in the specified sequence or a default value if the index is out of range.
source: IEnumerable<TSource>
An IEnumerable<TSource>
to return an element from.
index: int
The zero-based index of the element to retrieve.
TSource
The element at the specified position in the source sequence, or the default value for type TSource
if the index is out of range.
This method is similar to the ElementAt
method, but it returns a default value instead of throwing an exception if the index is out of range.
If TSource
is a reference type, the default value is null
. If TSource
is a value type, the default value is 0 for numeric types, false
for boolean, and '\0'
for char.
// Sample usage of ElementAtOrDefault with default value
var numbers = new List<int> { 1, 2, 3, 4, 5 };
// Get the element at index 2 (which is 3)
int elementAtIndex2 = numbers.ElementAtOrDefault(2);
Console.WriteLine($"Element at index 2: {elementAtIndex2}"); // Output: Element at index 2: 3
// Try to get an element at an index that is out of range
int elementAtOutOfRange = numbers.ElementAtOrDefault(10);
Console.WriteLine($"Element at index 10: {elementAtOutOfRange}"); // Output: Element at index 10: 0 (default value for int)
Returns the element at the specified position in the specified sequence or a specified default value if the index is out of range.
source: IEnumerable<TSource>
An IEnumerable<TSource>
to return an element from.
index: int
The zero-based index of the element to retrieve.
defaultValue: TSource
The value to return if the index is out of range.
TSource
The element at the specified position in the source sequence, or the specified default value if the index is out of range.
This overload allows you to specify a custom default value to be returned when the index is out of range.
// Sample usage of ElementAtOrDefault with a custom default value
var names = new List<string> { "Alice", "Bob", "Charlie" };
// Get the element at index 1 (which is "Bob")
string nameAtIndex1 = names.ElementAtOrDefault(1, "Unknown");
Console.WriteLine($"Name at index 1: {nameAtIndex1}"); // Output: Name at index 1: Bob
// Try to get an element at an index that is out of range, with a custom default value
string nameAtOutOfRange = names.ElementAtOrDefault(5, "Not Found");
Console.WriteLine($"Name at index 5: {nameAtOutOfRange}"); // Output: Name at index 5: Not Found