
You have an IEnumerable collection in your C# program and want to get an element at a specific index. In many IEnumerable types, you cannot index a certain element directly. Instead of using a foreach-loop or other techniques, we can use the ElementAt method from the System.Linq namespace.

To start, this program uses an array of three string literal elements. Arrays are IEnumerable collections, so we can index this array through the ElementAt method in the System.Linq namespace. The method calls with arguments 0, 1 and 2 succeed and return the target elements; the method call with argument 3 throws a System.ArgumentOutOfRangeException.
This C# example program uses the ElementAt extension method from System.Linq.
Program that uses ElementAt method [C#]
using System;
using System.Linq;
class Program
{
static void Main()
{
// Input array.
string[] array = { "Dot", "Net", "Perls" };
// Test ElementAt for 0, 1, 2.
string a = array.ElementAt(0);
Console.WriteLine(a);
string b = array.ElementAt(1);
Console.WriteLine(b);
string c = array.ElementAt(2);
Console.WriteLine(c);
// This is out of range.
string d = array.ElementAt(3);
}
}
Output
Dot
Net
Perls
Unhandled Exception: System.ArgumentOutOfRangeException: Index was out of range.Real-world usage. This program does not really demonstrate real-world usage of the ElementAt method. In this program, we could just directly use the indexer on the array variable itself. However, if for some reason we only knew the type of the collection was IEnumerable, we could use ElementAt more realistically.

The ElementAt method in the System.Linq namespace in the C# programming language provides a way for you to access specific elements in an IEnumerable collection without using a foreach-loop construct or any other expression. If an element does not exist at that index, you will receive an ArgumentOutOfRangeException.
LINQ Examples