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
The major difference between First and FirstOrDefault is that First() will throw an exception if there is no result data for the supplied criteria whereas FirstOrDefault() will return the default value (null) if there is no result data. First() will throw an exception if there is no result data, as you can see below.
When you want a default value is returned if the result set contains no record, use SingleOrDefault. When you always want one record no matter what the result set contains, use First or FirstOrDefault. When you want a default value if the result set contains no record, use FirstOrDefault.
Single() asserts that one and only one element exists in the sequence. First() simply gives you the first one. Use Single / SingleOrDefault() when you sure there is only one record present in database or you can say if you querying on database with help of primary key of table.
To respond directly to your specific question (why use First
if you can always use FirstOrDefault
), there are instances where you cannot use FirstOrDefault
, 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 use First
or first check if there are Any
elements, which requires double-enumeration.
This is especially true for value-typed enumerables, such as int[]
. default(int)
is 0
, which is also most likely a valid value of the array.
In general, the two methods represent different logical flows. First
would 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. FirstOrDefault
returns null on an empty set, which means you need to do additional processing with the returned value. This is similar logic to the Parse
vs TryParse
methods on int
/double
/etc. In fact, your question in some ways leads itself to the more general question of why to ever use exceptions.
Since First
throws an exception, it lends itself to all of the code-reuse opportunities that exceptions provide. For example, you could do:
try
{
x = arr1.First();
y = arr2.First();
z = arr3.First();
}
catch
{
throw new ArgumentException();
}
To explicitly force an exception to get raised versus performing a null
check.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With