What is the Difference Between First() and FirstOrDefault() in LINQ

/ / 0 Comments

In Linq, both First() and FirstOrDefault() are used to return the first element from a collection, and also it returns an element that satisfies the specified condition.

Below is the list of differences between First() and FirstOrDefault():

# About First() Method in Linq:

  • It returns the first element of a sequence.
  • If no element is present in the result, then it will throw an error as InvalidOperationException.
  • We should use the First() method, only when we are expected that more than one element and we want the first element.

# About FirstOrDefault() Method in Linq:

  • Same as First() it also returns the first element of a sequence but returns the default value if no result is found.
  • If no element is found, then it will return the default value i.e null for reference type and 0 for integer (value type).
  • We should use the FirstOrDefault() method when we are expecting more than one element and we want only the first element. Also if no element present then checks for the default value. 

The major difference between First() and FirstOrDefault() is First will throw an exception when there are no results and FirstOrDefault won't. In fact, FirstOrDefault will simply return the null value (reference types) or the default value of the value type.

Thank you for reading, pls keep visiting this blog and share this in your network. Also, I would love to hear your opinions down in the comments.

PS: If you found this content valuable and want to thank me? 👳 Buy Me a Coffee

Subscribe to our newsletter

Get the latest and greatest from Codepedia delivered straight to your inbox.


Post Comment

Your email address will not be published. Required fields are marked *

0 Comments