C# Enumerable ElementAtOrDefault

Description

Returns the element at a specified index in a sequence or a default value if the index is out of range.

Syntax


public static TSource ElementAtOrDefault<TSource>(
  this IEnumerable<TSource> source,
  int index
)

Parameters

  • TSource - The type of the elements of source.
  • source - An IEnumerable to return an element from.
  • index - The zero-based index of the element to retrieve.

Returns

Returns the element at a specified index in a sequence or a default value if the index is out of range.

Example

The following code example demonstrates how to use ElementAtOrDefault. This example uses an index that is outside the bounds of the array.


/*  ww w . j  av  a  2s. c  om*/

using System;
using System.Linq;
using System.Collections.Generic;
public class MainClass{
  public static void Main(String[] argv){  
    string[] names ={ "a", "ab", "abc","bb"};
    int index = 20;
    string name = names.ElementAtOrDefault(index);
    Console.WriteLine(name);

  }
}
    




















Home »
  C# Tutorial »
    System.Linq »




Enumerable