Linq First vs Single vs Last methods.

While using Linq developers often use extension methods First(), Single() and Last(). Another variation of these are FirstorDefault, LastorDefault and SingleOrDefault methods.

These methods are part of System.Linq namespace. The argument to these methods is a Predicate instance, it can be specified in the lambda syntax.

Let’s try to understand the usage and difference of each of these Linq methods using an example.

Let’s create a model class Employee having Code and Name as public properties:

Now add method in Program.cs of your console application to get employee data and display result on console:

First :

  • returns first element from the sequence.
  • Sequence (or collection) can have multiple result but the first element is returned.
  • If no matching element exists, we get an exception. Invalid operation exception: “Sequence contains no matching element”

FirstorDefault:

  • It is similar to First() except if no matching element is found it returns a default value (or null) where as First() gives us an exception in this case.
  • So, FirstorDefault is helpful if we are not sure whether a matching element exists in the collection.

Single:

  • returns result if only single i.e. only one element exists in the sequence.
  • it searches in collection for a single instance of an element matching a condition.
  • In case of more than single element, we get an exception (InvalidOperationException).
  • Useful when retrieving elements based on Primary key. Having multiple elements with same primary key is invalid hence exception should be raised.

SingleorDefault:

  • Similar to Single but returns default value if no matching element exists.
  • It also raises exception like Single if more than one element is found for a given condition.

Last:

  • Returns last element of a sequence.
  • Least used method among First, Single and Last.

LastorDefault:

  • Similar to Last but returns default value if no matching element exists.

Conclusion

SingleFirstLast
Description: Returns a single, specific element of a sequenceReturns the first element of a sequenceReturns last element of a sequence
Usage: When only single element is expected When first element is needed out of one or more than one elements.Least used.
when last element is needed out of multiple elements.
Error condition: Zero or more than one matching elements exists.No matching element in the collection. No matching element in the collection.