How to select the last record using a LINQ query

Introduction


In order to select the last record from a list of entities with LINQ, we use the Last or the LastOrDefault methods.

Last


The Last method returns the last element of a list , or an InvalidOperationException if the list of elements is empty.

System.InvalidOperationException: 'Sequence contains no elements'

LastOrDefault


The LastOrDefault method returns the last element of a list , or a Default value if the list of elements is empty.

  • If the empty list is a list of integer values, then the default value is 0

  • If the empty list is a list of boolean values, then the default value is false

  • If the empty list is a list of nullable values, then the default value is null

See the Default values table in C#

Examples


Non empty list

List<int> list = new List<int> { 5, 10, 12, 7, 99};

int value1 = list.Last();  // 99
int value2 = list.LastOrDefault();  // 99

Empty list

List<int> list = new List<int> { };

int value1 = list.Last();  // InvalidOperationException
int value2 = list.LastOrDefault();  // 0

List of nullable values

List<string> list = new List<string> { };

string value1 = list.Last();  // InvalidOperationException
string value2 = list.LastOrDefault();  // null

Namespace


To use the Last or the LastOrDefault methods, you have to include this namespace:

using System.Linq;

See also