[LINQ Operators] ElementAt

The “ElementAt” operator returns the element at a given index (zero-based) in a sequence.

 

1. Sample Data Objects

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

 

2. “ElementAt” operator

  • NonDeferred operator
  • Purpose: Element

 

3. Prototypes

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

The “ElementAt()” operator returns the element at a specified index in a sequence. It throws an exception if the index is out of range.¬† You can use the “ElementAtOrDefault()” operator if you do not want an exception.

 

4. Example 1 (Standard Operator)

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

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

try
{
  Employee emp1 =
    emps.Where(e => e.Name.Contains("Smith")).ElementAt(2); // error
}
catch
{
  Console.WriteLine("Out of Index");
}

 

5. Example 2 (Query Expression)

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

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

Employee emp
  = (from e in emps
     where e.Name.Contains("Smith")
     select e).ElementAt(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