CSharp - LINQ ElementAt

Introduction

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

Prototypes

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

An ArgumentOutOfRangeException is thrown if the index is less than zero or greater than or equal to the number of elements in the sequence.

Exceptions

  • ArgumentNullException is thrown if the source argument is null.
  • ArgumentOutOfRangeException is thrown if the index is less than zero or greater than or equal to the number of elements in the sequence.

Demo

using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
class Program/*  www.  j a v  a 2  s . co m*/
{
    static void Main(string[] args)
    {
        Student emp = Student.GetStudentsArray().ElementAt(3);

        Console.WriteLine("{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