LINQ ElementAt Method

  Total Views : 201
  Comments : 0
 
  Keywords : Linq elementat elements operator in c# / vb.net with example, How to use linq elementat method in c# / vb.net with example, Linq elementat method to get elements at specified index example

Here we will learn LINQ ElementAt() method in c#, vb.net with example and how to use LINQ ElementAt() method to get elements from list / collection based on specified index position in c#, vb.net with example.

LINQ ElementAt() Method

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

 

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

Syntax of LINQ ElementAt() Method

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

 

C# Code

 

int result = objList.ElementAt(1);

VB.NET Code

 

Dim result As Integer = objList.ElementAt(1)

If you observe above syntax we are getting element at second index position element from collection.

Example of LINQ ElementAt() Method

Following is the example of using LINQ EelementAt() method to get elements at 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 above example we are trying to get different elements in collection based on different index positions.

Output of LINQ ElementAt() Method Example

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

 

Element At Index 1: 2

Element At Index 3: 4

In case if we pass the index position which is not exists in list / collection then it will throw “ArgumentOutOfRangeException” error.

 

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

 Comments (0)

Be the first to give your valuable feedback

Leave a comment

  • Default Tutlane User