.NET API Documentation

Explore the .NET Class Library

System.Linq.ElementAt

Namespace: System.Linq

Returns the element at a specified index in a sequence.

public static TSource ElementAt(this IEnumerable source, int index)

Parameters

source
IEnumerable<TSource>
The IEnumerable<T> to return an element from.
index
int
The zero-based index of the element to retrieve.

Returns

TSource
The element at the specified position in the source sequence.

Exceptions

ArgumentNullException
source is null.
ArgumentOutOfRangeException
index is less than 0 or greater than or equal to the number of elements in source.

Example

The following code example demonstrates how to use the ElementAt method to retrieve an element at a specific index.


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

public class ElementAtExample
{
    public static void Main(string[] args)
    {
        List<string> fruits = new List<string> { "Apple", "Banana", "Cherry", "Date", "Elderberry" };

        // Get the element at index 2 (Cherry)
        string fruitAtIndex2 = fruits.ElementAt(2);
        Console.WriteLine($"Fruit at index 2: {fruitAtIndex2}"); // Output: Fruit at index 2: Cherry

        // Get the element at the last index (Elderberry)
        string lastFruit = fruits.ElementAt(fruits.Count - 1);
        Console.WriteLine($"Last fruit: {lastFruit}"); // Output: Last fruit: Elderberry

        try
        {
            // Attempt to get an element at an invalid index
            string invalidFruit = fruits.ElementAt(10);
        }
        catch (ArgumentOutOfRangeException ex)
        {
            Console.WriteLine($"Error: {ex.Message}");
            // Output: Error: Index was out of range. Must be non-negative and less than the size of the collection. (Parameter 'index')
        }
    }
}
                

Remarks

The ElementAt method is generally not recommended for collections that do not provide efficient random access (e.g., LinkedList<T>). For such collections, iterating through the elements to find the one at the specified index can be inefficient.

For better performance with collections that support it, consider using ElementAtOrDefault or indexing directly if the collection implements IList<T>.