CSharp - LINQ ElementAtOrDefault

Introduction

The ElementAtOrDefault operator returns the element from the source sequence at the specified index.

Prototypes

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

If the index is less than zero or greater than or equal to the number of elements in the sequence, default(T) is returned.

For reference and nullable types, the default value is null.

Exceptions

ArgumentNullException is thrown if the source argument is null.

Demo

using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
class Program/*from w  w  w  . j av a  2  s. com*/
{
    static void Main(string[] args)
    {
        Student emp = Student.GetStudentsArray()
          .ElementAtOrDefault(3);

        Console.WriteLine(emp == null ? "NULL" :
          string.Format("{0} {1}", emp.firstName, emp.lastName));

        emp = Student.GetStudentsArray()
          .ElementAtOrDefault(5);

        Console.WriteLine(emp == null ? "NULL" :
        string.Format("{0} {1}", emp.firstName, emp.lastName));
    }
}
class Student
{
    public int id;
    public string firstName;
    public string lastName;

    public static ArrayList GetStudentsArrayList()
    {
        ArrayList al = new ArrayList();

        al.Add(new Student { id = 1, firstName = "Joe", lastName = "Ruby" });
        al.Add(new Student { id = 2, firstName = "Windows", lastName = "Python" });
        al.Add(new Student { id = 3, firstName = "Application", lastName = "HTML" });
        al.Add(new Student { id = 4, firstName = "David", lastName = "Visual" });
        al.Add(new Student { id = 101, firstName = "Kotlin", lastName = "Fortran" });
        return (al);
    }

    public static Student[] GetStudentsArray()
    {
        return ((Student[])GetStudentsArrayList().ToArray());
    }
}

Result

There is no element whose index is 5.