Possible Duplicate:
When to use .First and when to use .FirstOrDefault with LINQ?
What is the point of using the First operator in LINQ, when you could use the FirstOrDefault operator instead?
var q = results.First(); // Error if empty
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
To respond directly to your specific question (why use
Firstif you can always useFirstOrDefault), there are instances where you cannot useFirstOrDefault, because it loses information! The “default value” is likely a valid element type in the source list. You have no way to distinguish between the first element in the enumeration being null/default vs. there being no elements in the list unless you useFirstor first check if there areAnyelements, which requires double-enumeration.This is especially true for value-typed enumerables, such as
int[].default(int)is0, which is also most likely a valid value of the array.In general, the two methods represent different logical flows.
Firstwould be used if not having any elements is “exceptional” (an error), which then want to handle out-of-band in your application. In this scenario, you “expect” to have at least one element.FirstOrDefaultreturns null on an empty set, which means you need to do additional processing with the returned value. This is similar logic to theParsevsTryParsemethods onint/double/etc. In fact, your question in some ways leads itself to the more general question of why to ever use exceptions.Since
Firstthrows an exception, it lends itself to all of the code-reuse opportunities that exceptions provide. For example, you could do: