Differences between FirstOrDefault() and SingleOrDefault()

The usage of this extension methods depends on the situation. But I’m going to list the main differences:

  • FirstOrDefault()
  • – you clearly sure, that the query can return any amount of results, but you state, that you only want the first one

  • SingleOrDefault()
  • – you clearly sure, that the query should result in at most a single result

If result set returns many records:

  • SingleOrDefault() – throws an exception
  • FirstOrDefault() – returns the first record

Look at this table to view info in more memorable way

0 VALUES 1 VALUE MORE THAN 1 VALUE
FirstOrDefault() Default First First
SingleOrDefault() Default First Exception

To sum up,

  • FirstOrDefault() Returns any number of results, but I only care about the first one, there may also be no results.
  • SingleOrDefault() There are 1 or 0 results, if there are more that means there’s an error somewhere.
  • First() There is at least one result, and I want it ,an exception if no result returned.
  • Single() There is exactly 1 result, no more, no less, and I want that on, an exception if no result returned.
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