[LINQ Operators] ElementAtOrDefault

The “ElementAtOrDefault” operator returns the element at a given index (zero-based) in a sequence, or a default value if the index is out of range.

 

1. Sample Data Objects

To test examples, you need to include the <data classes> in your project.

 

2. “ElementAtOrDefault” operator

  • NonDeferred operator
  • Purpose: Element

 

3. Prototypes

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

The “ElementAtOrDefault()” operator returns the element at a specified index in a sequence. If the index is out of range, it returns a default value of the type.

 

4. Example 1 (Standard Operator)

IEnumerable<Employee> emps = Employee.GetEmployees();

Employee emp =
  emps.Where(e => e.Name.Contains("Smith"))
  .ElementAtOrDefault(1);
Console.WriteLine("Matching Employee: {0}", emp.Name); // Mark Smith

Employee emp1 =
  emps.Where(e => e.Name.Contains("Smith"))
  .ElementAtOrDefault(2); // out of index
if (emp1 == null)
{
  Console.WriteLine("Out of Index");
}

 

5. Example 2 (Query Expression)

There’s no corresponding query expression for the “ElementAtOrDefault()” operator.

IEnumerable<Employee> emps = Employee.GetEmployees();

Employee emp =
  (from e in emps
  where e.Name.Contains("Smith")
  select e)
  .ElementAtOrDefault(1); // Mark Smith

Console.WriteLine("Matching Employee: {0}", emp.Name);

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s