ElementAtOrDefault<TSource>(Int32) Method

Namespace: System.Linq
Assembly: System.Core.dll

Returns the element at a specified index in a sequence or a default value if the index is out of range.

This method is used to retrieve an element from a sequence at a specific zero-based index. If the index is less than zero or greater than or equal to the number of elements in the sequence, the method returns the specified default value instead of throwing an exception.

Syntax

public static TSource ElementAtOrDefault<TSource>(this IEnumerable<TSource> source, int index)
public static TSource ElementAtOrDefault<TSource>(this IEnumerable<TSource> source, int index, TSource defaultValue)

Parameters

  • 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.

Type Parameters

  • TSource: The type of the elements in the sequence.

Examples

using System;
using System.Linq;

public class Example
{
    public static void Main()
    {
        int[] numbers = { 10, 20, 30, 40, 50 };

        // Get the element at index 2 (which is 30)
        int elementAtIndex2 = numbers.ElementAtOrDefault(2);
        Console.WriteLine($"Element at index 2: {elementAtIndex2}"); // Output: Element at index 2: 30

        // Get the element at index 5 (out of range) with default value 0
        int elementAtIndex5WithDefault = numbers.ElementAtOrDefault(5, 0);
        Console.WriteLine($"Element at index 5 (default 0): {elementAtIndex5WithDefault}"); // Output: Element at index 5 (default 0): 0

        // Get the element at index 10 (out of range) with default value -1
        int elementAtIndex10WithDefault = numbers.ElementAtOrDefault(10, -1);
        Console.WriteLine($"Element at index 10 (default -1): {elementAtIndex10WithDefault}"); // Output: Element at index 10 (default -1): -1

        // Get the element at index -1 (out of range) with default value null for nullable type
        int?[] nullableNumbers = { 1, 2, 3 };
        int? elementAtNegativeOne = nullableNumbers.ElementAtOrDefault(-1);
        Console.WriteLine($"Element at index -1 (nullable): {elementAtNegativeOne}"); // Output: Element at index -1 (nullable):
    }
}
                    

Remarks

If the source sequence is empty, this method returns the defaultValue. If the index parameter is negative, this method returns the defaultValue.

This method uses zero-based indexing.

The overload without a defaultValue parameter uses the default value for the type TSource. For reference types, this is null. For value types, this is the value that results from calling the parameterless constructor of the type (e.g., 0 for int, false for bool).

See Also