What is difference between First and FirstOrDefault in LINQ?

 

.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)

Linq

 

 

 

 

 

 

.First()

  • 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

 .FirstOfDefault()

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s