How to select the first record using a LINQ query

Introduction


In order to select the first record from a list of entities with LINQ, we use the First or the FirstOrDefault methods.

First


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

System.InvalidOperationException: 'Sequence contains no elements'

FirstOrDefault


The FirstOrDefault method returns the first 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> { 14, 3, 29, 100, 15};

int value1 = list.FirstOrDefault();  // 14
int value2 = list.First();  // 14

Empty list

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

int value1 = list.FirstOrDefault();  // 0
int value2 = list.First();  // InvalidOperationException

List of nullable values

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

string value1 = list.FirstOrDefault();  // null
string value2 = list.First();  // InvalidOperationException

Namespace


To use the First or the FirstOrDefault methods, you have to include this namespace:

using System.Linq;

See also