LINQ ElementAt Method

In LINQ, ElementAt() operator is used to return element from list / collection based on specified index position.

 

Generally, the list index will start with zero, so we need to send zero (0) as the index position if we want to get the first element.

Syntax of LINQ ElementAt() Method

Following is the syntax of using the LINQ ElementAt() method to get elements at specified index positions in the list/collection.

 

C# Code

 

int result = objList.ElementAt(1);

VB.NET Code

 

Dim result As Integer = objList.ElementAt(1)

If you observe the above syntax, we get elements at the second index position element from the collection.

Example of LINQ ElementAt() Method

Following is the example of using the LINQ EelementAt() method to get elements at a specified index position.

 

C# Code

 

using System;
using System.Linq;

namespace LINQExamples
{
  class Program
  {
    static void Main(string[] args)
    {
      int[] objList = { 1, 2, 3, 4, 5 };
      int result = objList.ElementAt(1);
      int val = objList.ElementAt(3);
      Console.WriteLine("Element At Index 1: {0}", result);
      Console.WriteLine("Element At Index 3: {0}", val);
      Console.ReadLine();
    }
  }
}

VB.NET Code

 

Module Module1

Sub Main()
Dim objList As Integer() = {1, 2, 3, 4, 5}
Dim result As Integer = objList.ElementAt(1)
Dim val As Integer = objList.ElementAt(3)
Console.WriteLine("Element At Index 1: {0}", result)
Console.WriteLine("Element At Index 3: {0}", val)
Console.ReadLine()
End Sub
End Module

If you observe the above example, we are trying to get different elements in the collection based on different index positions.

Output of LINQ ElementAt() Method Example

Following is the result of the LINQ ElementAt() method example.

 

Element At Index 1: 2
Element At Index 3: 4

In case if we pass the index position that does not exist in the list/collection, it will throw an “ArgumentOutOfRangeException” error.

 

This is how we can use LINQ EelementAt() method to get the element at a specified index position in c#, vb.net.