
The ElementAtOrDefault method of System.Linq.Queryable class enables to get the element at specified index or it returns a default value if the specified index is out of range. The LINQ ElementAtOrDefault method accepts only one parameter as integer type that returns a particular element from the sequence. If the specified index does not exist then this method returns default value based on the data type of element of the sequence or returns null for Nullable types. The Linq ElementAtOrDefault method does not have any overloaded function. It has a following single form:
public static TSource ElementAtOrDefault<TSource>(this IQueryable<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 ElementAtOrDefault 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.AsQueryable().ElementAtOrDefault(4);
Response.Output.Write("{0} {1}<br />", employee.FirstName, employee.LastName);
employee = Employees.AsQueryable().ElementAtOrDefault(15);
if (employee != null)
Response.Output.Write("{0} {1}<br />", employee.FirstName, employee.LastName);
else
Response.Output.Write("No item found.<br />");
// Output:
// Lance Tucker
// No item found.
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 ElementAtOrDefault method two times. First we have specified the index within the range of List collection. In the second call to ElementAtOrDefault method we have specified the index out of range of List collection that will return a null object for Employee class object.