System.Linq.Enumerable.ElementAt

public static TSource ElementAt(this IEnumerable<TSource> source, int index)
Returns the element at a specified index in a sequence.

Parameters

source
The IEnumerable<TSource> to return the element from.
index
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.

Remarks

This method enforces the use of zero-based indexing.

If the type of source implements the IList<TSource> interface, that implementation's get_Item(int) method is used. Otherwise, this method iterates through the sequence and returns the element at the specified index.

Example


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

public class Example
{
    public static void Main(string[] args)
    {
        List<int> numbers = new List<int> { 5, 4, 3, 2, 1 };

        // Get the element at index 2 (which is 3)
        int element = numbers.ElementAt(2);

        Console.WriteLine(element); // Output: 3
    }
}