I\'ve searched around and haven\'t really found a clear answer as to when you\'d want to use .First
and when you\'d want to use .FirstOrDefault
wit
This type of the function belongs to element operators. Some useful element operators are defined below.
We use element operators when we need to select a single element from a sequence based on a certain condition. Here is an example.
List items = new List() { 8, 5, 2, 4, 2, 6, 9, 2, 10 };
First() operator returns the first element of a sequence after satisfied the condition. If no element is found then it will throw an exception.
int result = items.Where(item => item == 2).First();
FirstOrDefault() operator returns the first element of a sequence after satisfied the condition. If no element is found then it will return default value of that type.
int result1 = items.Where(item => item == 2).FirstOrDefault();