C# LINQ Enumerable.ElementAt Method in ASP.Net
The ElementAt method of System.Linq.Enumerable class allows to get the element at the specified index in a sequence. The LINQ ElementAt method accepts only one parameter as integer type that returns that particular element from the sequence. If the specified index does not exist then this method throws an exception of index is out of range. The Linq ElementAt method does not have any overloaded function. It has a following single form:
public static TSource ElementAt<TSource>(this IEnumerable<TSource> source, int index);
It accepts an integer type value to specify the index and returns the element from a sequence at that index.
C# LINQ ElementAt Method Example in ASP.Net
List<Employee> Employees = new List<Employee>()
{
new Employee(1, "Terry", "Adams", 30, 5),
new Employee(2, "Hugo", "Garcia", 27, 3),
new Employee(3, "Fadi", "Fakhouri", 32, 5),
new Employee(4, "Debra", "Garcia", 30, 4),
new Employee(5, "Lance", "Tucker", 35, 7),
new Employee(6, "Hanying", "Feng", 35, 5),
new Employee(7, "Michael", "Tucker", 28, 5),
new Employee(8, "Eugene", "Zabokritski", 40, 10),
new Employee(9, "Sven", "Mortensen", 37, 8),
new Employee(10, "Svetlana", "Omelchenko", 36, 7)
};
Employee employee = Employees.ElementAt(4);
Response.Output.Write("{0} {1}<br />", employee.FirstName, employee.LastName);
try
{
// System.ArgumentOutOfRangeException: Index was out of range.
// Must be non-negative and less than the size of the collection.
// Parameter name: index
employee = Employees.ElementAt(15);
if (employee != null)
Response.Output.Write("{0} {1}<br />", employee.FirstName, employee.LastName);
}
catch(Exception ex)
{
Response.Output.Write("{0}<br />", ex.Message);
}
// Output:
// Lance Tucker
// Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index
C# Employee Class:
public class Employee
{
public int ID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
public int Experience { get; set; }
public Employee(int Id, string firstName, string lastName, int age, int experience)
{
this.ID = Id;
this.FirstName = firstName;
this.LastName = lastName;
this.Age = age;
this.Experience = experience;
}
}
In the above C# sample we have tried the Linq ElementAt method two times. First we have specified the index within the range of List collection. In the second call to ElementAt method we have specified the index out of range of List collection that will throw an exception of index out of range immediately at the time of invocation.
Continue to the next tutorial: C# LINQ Enumerable.ElementAtOrDefault Method in ASP.Net to learn how to get the default value if the specified index is out of range.

* will not be published
* hint: http://www.example.com