[LINQ Operators] First

The “First” operator returns the first element of a sequence or throws an exception if no element is found. You can provide the predicate delegate instead of using the “Where” operator.

 

1. Sample Data Object

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

 

2. “First” operator

  • NonDeferred operator
  • Purpose: Element

 

3. Prototypes

public static T First<T>(
  this IEnumerable<T> source)

public static T First<T>(
  this IEnumerable<T> source,
  Func<T, bool> predicate)

The “First()” operator returns the first element in a sequence. In the second syntax, you can provide the condition and you do not need to use the “Where” operator. The “First()” operator throws an exception when there’s no element to return. Therefore, you need to use the operator in a “try/catch” block or use the “FirstOrDefault()” operator instead.

 

4. Example 1 (Standard Operator)

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

Employee emp =
  emps.Where(e => e.Name.Contains("Smith")).First();
Console.WriteLine($"First Matching Employee: {emp.Name}"); // Jane Smith

try
{
  Employee emp1 =
    emps.Where(e => e.Name.Contains("NoName")).First();
}
catch
{
  Console.WriteLine("Cannot find any employee");
}

 

5. Example 2 (Query Expression)

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

 

6. Example 3 (Standard Operator) – with a condition

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

Employee emp =
  emps.First(e => e.Name.Contains("Smith"));

Console.WriteLine($"First Matching Employee: {emp.Name}"); // Jane Smith

This example is the same as the previous one but it is simpler.

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