LINQ ElementAtOrDefault() Method

In LINQ, the ElementAtOrDefault operator is used to get the element at a specified index position in list/collection, and it’s same as LINQ ElementAt() method, but the only difference is it will return default value in case if the specified index position element does not exist in the list.

Syntax of LINQ ElementAtOrDefault() Method

Following is the syntax of using the LINQ ElementAtOrDefault() method to get elements at a specified index position or a default value if the specified index position element does not exist in the collection.

 

C# Code

 

int result = objList.ElementAtOrDefault(1);

VB.NET Code

 

Dim result As Integer = objList.ElementAtOrDefault(1)

If you observe the above syntax, we get elements at a specified index position.

Example of LINQ ElementAtOrDefault() Method

Following is the example of the LINQ ElementAtOrDefault() method to get elements at the 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.ElementAtOrDefault(1);
      int val = objList.ElementAtOrDefault(3);
      int val1 = objList.ElementAtOrDefault(10);
      Console.WriteLine("Element At Index 1: {0}", result);
      Console.WriteLine("Element At Index 3: {0}", val);
      Console.WriteLine("Element At Index 10: {0}", val1);
      Console.ReadLine();
    }
  }
}

VB.NET Code

 

Module Module1

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

The above example shows that we are getting different elements from the list based on specified index positions. Here we specified index position “10” which is not in the list; in this case, it will return a default value.

Result of LINQ ElementAtOrDefault() Example

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

 

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

This is how we can use LINQ ElementAtOrDefault() method in c#, vb.net to get element or default value from a list based on the specified index position.