When to use First() and when to use FirstOrDefault() with LINQ?

Technology CommunityCategory: LINQWhen to use First() and when to use FirstOrDefault() with LINQ?
VietMX Staff asked 3 years ago
  • Use First() when you know or expect the sequence to have at least one element. In other words, when it is an exceptional occurrence that the sequence is empty.
  • Use FirstOrDefault() when you know that you will need to check whether there was an element or not. In other words, when it is legal for the sequence to be empty. You should not rely on exception handling for the check. (It is bad practice and might hurt performance).

First() will throw an exception if there’s no row to be returned, while FirstOrDefault() will return the default value (NULL for all reference types) instead.