.First() will throw an exception if there’s no row to be returned, while .FirstOfDefault() will return a NULL value instead. .FirstOfDefault() will simply return either null (reference types) or the default value of the value type. (e.g like ‘0’ for an int.) .FirstOfDefault() is preferred when you’re not sure if you’re going to get results out of your query. When logically the data should be there, exception handling can be considered. Between .First() and .FirstOfDefault(), you should use .First() when you’re sure that an element exists and if it doesn’t, then there’s an error.
someList.First(); // exception if collection is empty. someList.FirstOrDefault(); // first item or default(Type)
- Returns the first element of a sequence
- Throws exception: There are no elements in the result
- Use when: When more than 1 element is expected and you want only the first
- Returns the first element of a sequence, or a default value if no element is found
- Throws exception: Only if the source is null
- Use when: When more than 1 element is expected and you want only the first. Also it is ok for the result to be empty