19

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


  • I could see a close for a duplicate, but ... "not constructive"? :( Although, I think the question could use clarification as to why First (with Error-if-empty) is thought to be less ideal than FirstOrDefault. - user166390

3 답변


17

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();
}


8

To explicitly force an exception to get raised versus performing a null check.


2

It's the same discussion as Int32.Parse vs. Int32.TryParse. The former throws an exception in case of failure, the latter returns false and the program continues smoothly...

Linked


Related

Latest