871

I've searched around and haven't really found a clear answer as to when you'd want to use .First and when you'd want to use .FirstOrDefault with LINQ.

  • When would you want to use .First? Only when you'd want to catch the exception if no results where returned?

    var result = List.Where(x => x == "foo").First();
    
  • And when would you want to use .FirstOrDefault? When you'd always want the default type if no result?

    var result = List.Where(x => x == "foo").FirstOrDefault();
    
  • And for that matter, what about Take?

    var result = List.Where(x => x == "foo").Take(1);
    
BoltClock
  • 630,065
  • 150
  • 1,295
  • 1,284
Metro Smurf
  • 33,866
  • 20
  • 97
  • 127
  • 89
    `.First` and `.FirstOrDefault` both take predicates as arguments, so `var result = List.Where(x => x == "foo").First();` could be rewritten as `var result = List.First(x => x == "foo");` – Rian Schmits Jun 22 '11 at 15:39
  • 62
    Don't forget to consider `Single` and `SingleOrDefault`. I hate when people use `First` when they really mean `Single` ; ) – BartoszKP Sep 22 '13 at 00:33
  • 24
    Single or SingleOrDefault would throw an exception if there are more than one element returned! I think FirstOrDefault is better in most common cases! – Eric Draven Mar 31 '16 at 13:33
  • 22
    The point is when you expect a Single result you should say so, and the exception indicates your logic failed. – NetMage Oct 24 '16 at 20:57
  • 2
    Also consider that using `.FirstOrDefault()` always gives you the opportunity to throw a more meaningful exception. If a sequence exception is thrown and more than one `.First()` in a method, it can be difficult to discern which statement is the problem. – StingyJack Nov 06 '17 at 14:00
  • 2
    Excellent article that explains it in its entirety. http://www.donnfelker.com/linq-single-vs-first/ – Latency Dec 22 '17 at 10:19
  • Much could be said either way. Much of coding is handling 'bad paths' -- cases where you don't connect to a database, don't get a result, could face division by 0, etc. Thus, exception-handling. Still .FirstOrDefault() is a sort of fail-safe, and when I was doing LINQ (which I don't currently do) it is what I preferred. I liked the baked-in safety. But there are valid arguments against it also. – JosephDoggie Apr 09 '21 at 13:11
  • @NetMage, but you also have a performance penalty of having to go through the whole collection to verify that. If you want to indicate your logic a comment is free. Making your code twice as slow is not. – Paul Childs Apr 14 '21 at 04:17
  • @PaulChilds What makes you think that? `Single` checks if the source has 0, 1 or more elements, and throws an exception for 0 or `> 1` - if it is `IList` it uses the count directly, if not it calls `MoveNext` twice at most. Bad code that runs faster isn't useful. – NetMage Apr 14 '21 at 23:23
  • FirstOrDefault does not enumerate the whole queried collection whereas Single does. This means e.g. that FirstOrDefault(x => x == "foo") can make an early exit. Single cannot optimise. – Paul Childs Apr 15 '21 at 01:22

14 Answers14

843

I would use First() when I know or expect the sequence to have at least one element. In other words, when it is an exceptional occurrence that the sequence is empty.

Use FirstOrDefault() when you know that you will need to check whether there was an element or not. In other words, when it is legal for the sequence to be empty. You should not rely on exception handling for the check. (It is bad practice and might hurt performance).

Finally, the difference between First() and Take(1) is that First() returns the element itself, while Take(1) returns a sequence of elements that contains exactly one element.

jpaugh
  • 5,719
  • 4
  • 33
  • 83
driis
  • 151,614
  • 43
  • 262
  • 332
  • 6
    The only thing I'd add is that if the default value for the type you're selecting could be a valid value, for instance your result might be the int value 0, then handling the exception seems to be the best way to handle this. – PeterBelm Apr 19 '12 at 08:59
  • 27
    Scratch that, I've found a much nicer way of accomplishing that, use: DefaultIfEmpty(-1).First() – PeterBelm Apr 19 '12 at 09:03
  • 9
    Take does not return exactly one element, it returns at most one element (if you specify 1, of course). It might as well return 0 elements, if the sequence is initially empty. – SPIRiT_1984 May 16 '12 at 07:12
  • WTF ? **while Take() returns a sequence of elements that contains exactly one element** ? – Royi Namir Jan 21 '15 at 08:54
  • 4
    @RoyiNamir, yes in the context of the question where the parameter to take is 1. I also noted that in parens immediately after that sentence. – driis Jan 21 '15 at 17:48
  • 2
    I think it would be better if you explained how `Take` worked, then explain how `First()` is the same as `Take(1)` – Trisped Feb 21 '15 at 05:26
  • I'll add, that First() throws an exception not only when the sequence is empty, but also when nothing in the sequence satisfies the condition in First(value => SomeCondition(value)) – ZuoLi Jun 02 '15 at 07:40
  • 1
    Suppose `source` is an `IEnumerable` that we know might be empty. Then `.FirstOrDefault()` can return `default(Item)` (i.e. `null`, `0`, etc.) in **two different ways**. The first situation is when `source` is non-empty and the first item in `source` happens to have the value `default(Item)`. The second situation is when `source` is empty (hence no "first" item exists). If you want to distinguish these two scenarios, you can use `.Take(1)`. That will give you a singleton (count is 1) sequence in the first scenario, and an empty sequence in the second one. – Jeppe Stig Nielsen Jan 28 '16 at 13:03
  • +1 yet Take returns an IEnumerable and not a single T, so its plain out of scope. Handle the error or handle the null is what is all about - that is perfect correct. – Stefanos Zilellis Oct 25 '20 at 15:43
279

.First will throw an exception when there are no results. .FirstOrDefault won't, it will simply return either null (reference types) or the default value of the value type. (e.g like 0 for an int.) The question here is not when you want the default type, but more: Are you willing to handle an exception or handle a default value? Since exceptions should be exceptional, FirstOrDefault is preferred when you're not sure if you're going to get results out of your query. When logically the data should be there, exception handling can be considered.

Skip() and Take() are normally used when setting up paging in results. (Like showing the first 10 results, and the next 10 on the next page, etc.)

Hope this helps.

DIF
  • 2,440
  • 6
  • 36
  • 49
Jeroen Landheer
  • 7,600
  • 1
  • 32
  • 41
124

.First() will throw an exception if there's no row to be returned, while .FirstOrDefault() will return the default value (NULL for all reference types) instead.

So if you're prepared and willing to handle a possible exception, .First() is fine. If you prefer to check the return value for != null anyway, then .FirstOrDefault() is your better choice.

But I guess it's a bit of a personal preference, too. Use whichever makes more sense to you and fits your coding style better.

A. Gladkiy
  • 2,598
  • 3
  • 25
  • 51
marc_s
  • 675,133
  • 158
  • 1,253
  • 1,388
72

First()

  1. Returns first element of a sequence.
  2. It throw an error when There is no element in the result or source is null.
  3. you should use it,If more than one element is expected and you want only first element.

FirstOrDefault()

  1. Returns first element of a sequence, or a default value if no element is found.
  2. It throws an error Only if the source is null.
  3. you should use it, If more than one element is expected and you want only first element. Also good if result is empty.

We have an UserInfos table, which have some records as shown below. On the basis of this table below I have created example...

UserInfo Table

How to use First()

var result = dc.UserInfos.First(x => x.ID == 1);

There is only one record where ID== 1. Should return this record
ID: 1 First Name: Manish Last Name: Dubey Email: xyz@xyz.com

var result = dc.UserInfos.First(x => x.FName == "Rahul");   

There are multiple records where FName == "Rahul". First record should be return.
ID: 7 First Name: Rahul Last Name: Sharma Email: xyz1@xyz.com

var result = dc.UserInfos.First(x => x.ID ==13);

There is no record with ID== 13. An error should be occur.
InvalidOperationException: Sequence contains no elements

How to Use FirstOrDefault()

var result = dc.UserInfos.FirstOrDefault(x => x.ID == 1);

There is only one record where ID== 1. Should return this record
ID: 1 First Name: Manish Last Name: Dubey Email: xyz@xyz.com

var result = dc.UserInfos.FirstOrDefault(x => x.FName == "Rahul");

There are multiple records where FName == "Rahul". First record should be return.
ID: 7 First Name: Rahul Last Name: Sharma Email: xyz1@xyz.com

var result = dc.UserInfos.FirstOrDefault(x => x.ID ==13);

There is no record with ID== 13. The return value is null

Hope it will help you to understand when to use First() or FirstOrDefault().

p__d
  • 397
  • 1
  • 4
  • 18
Mukesh Kumar
  • 2,146
  • 4
  • 21
  • 35
  • 4
    In my opinion, the statement "An error should be occur." under the third FirstOrDefault()-example is misleading. – Jannik Sep 28 '15 at 07:55
21

First of all, Take is a completely different method. It returns an IEnumerable<T> and not a single T, so that's out.

Between First and FirstOrDefault, you should use First when you're sure that an element exists and if it doesn't, then there's an error.

By the way, if your sequence contains default(T) elements (e.g. null) and you need to distinguish between being empty and the first element being null, you can't use FirstOrDefault.

mmx
  • 390,062
  • 84
  • 829
  • 778
15

First:

  • Returns the first element of a sequence
  • Throws exception: There are no elements in the result
  • Use when: When more than 1 element is expected and you want only the first

FirstOrDefault:

  • Returns the first element of a sequence, or a default value if no element is found
  • Throws exception: Only if the source is null
  • Use when: When more than 1 element is expected and you want only the first. Also it is ok for the result to be empty

From: http://www.technicaloverload.com/linq-single-vs-singleordefault-vs-first-vs-firstordefault/

user2051770
  • 451
  • 4
  • 11
13

Another difference to note is that if you're debugging an application in a Production environment you might not have access to line numbers, so identifying which particular .First() statement in a method threw the exception may be difficult.

The exception message will also not include any Lambda expressions you might have used which would make any problem even are harder to debug.

That's why I always use FirstOrDefault() even though I know a null entry would constitute an exceptional situation.

var customer = context.Customers.FirstOrDefault(i => i.Id == customerId);
if (customer == null)
{
   throw new Exception(string.Format("Can't find customer {0}.", customerId));
}
Kye
  • 5,268
  • 9
  • 42
  • 79
7

First()

When you know that result contain more than 1 element expected and you should only the first element of sequence.

FirstOrDefault()

FirstOrDefault() is just like First() except that, if no element match the specified condition than it returns default value of underlying type of generic collection. It does not throw InvalidOperationException if no element found. But collection of element or a sequence is null than it throws an exception.

Nimesh khatri
  • 653
  • 9
  • 25
6

This type of the function belongs to element operators. Some useful element operators are defined below.

  1. First/FirstOrDefault
  2. Last/LastOrDefault
  3. Single/SingleOrDefault

We use element operators when we need to select a single element from a sequence based on a certain condition. Here is an example.

  List<int> items = new List<int>() { 8, 5, 2, 4, 2, 6, 9, 2, 10 };

First() operator returns the first element of a sequence after satisfied the condition. If no element is found then it will throw an exception.

int result = items.Where(item => item == 2).First();

FirstOrDefault() operator returns the first element of a sequence after satisfied the condition. If no element is found then it will return default value of that type.

int result1 = items.Where(item => item == 2).FirstOrDefault();

Sheo Dayal Singh
  • 1,173
  • 14
  • 9
3

I found a website that apperars to explain the need for FirstOrDefault
http://thepursuitofalife.com/the-linq-firstordefault-method-and-null-resultsets/
If there are no results to a query, and you want to to call First() or Single() to get a single row... You will get an “Sequence contains no elements” exception.

Disclaimer: I have never used LINQ, so my apologies if this is way off the mark.

NULL
  • 109
  • 3
2
someList.First(); // exception if collection is empty.
someList.FirstOrDefault(); // first item or default(Type)

Which one to use? It should be decided by the business logic, and not the fear of exception/programm failure.

For instance, If business logic says that we can not have zero transactions on any working day (Just assume). Then you should not try to handle this scenario with some smart programming. I will always use First() over such collection, and let the program fail if something else screwed up the business logic.

Code:

var transactionsOnWorkingDay = GetTransactionOnLatestWorkingDay();
var justNeedOneToProcess = transactionsOnWorkingDay.First(): //Not FirstOrDefault()

I would like to see others comments over this.

Manish Basantani
  • 15,105
  • 22
  • 65
  • 96
  • The default value for reference and nullable types is null. – dsa May 20 '13 at 13:42
  • Failing quickly is good - however for the scenario you described, I'd rather see First, have it fail, catch the exception, and then return a meaningful error. Like catch(InvalidOperationException e){throw new InvalidOperationException("Cannot have zero transactions in a day!", e)}; But yeah, using default to avoid dealing with a real business logic problem is very bad. – Mathieson Sep 15 '14 at 15:08
2

Others have very well described the difference between First() and FirstOrDefault(). I want to take a further step in interpreting the semantics of these methods. In my opinion FirstOrDefault is being overused a lot. In the majority of the cases when you’re filtering data you would either expect to get back a collection of elements matching the logical condition or a single unique element by its unique identifier – such as a user, book, post etc... That’s why we can even get as far as saying that FirstOrDefault() is a code smell not because there is something wrong with it but because it’s being used way too often. This blog post explores the topic in details. IMO most of the times SingleOrDefault() is a much better alternative so watch out for this mistake and make sure you use the most appropriate method that clearly represents your contract and expectations.

Vasil Kosturski
  • 121
  • 1
  • 8
  • 1
    Depending on your context `.SingleOrDefault()` can just as easily be misused and can impact performace with certain types of queries. The underlying implementation of `.SingleOrDefault()` actually uses `.Take(2)` then applies validation logic. The code smell is more in why we use _OrDefault()_ at all, not neccessarily the _First_ vs _Single_ If our code has already pre-assumed or pre-validated that the condition will only ever return 1 or no rows, do we need to keep using and validating `.Single()` later in the method chain? – Chris Schaller Mar 03 '21 at 23:21
1

Ok let me give my two cents. First / Firstordefault are for when you use the second constructor. I won't explain what it is, but it's when you would potentially always use one because you don't want to cause an exception.

person = tmp.FirstOrDefault(new Func<Person, bool>((p) =>
{
    return string.IsNullOrEmpty(p.Relationship);
}));
BoltClock
  • 630,065
  • 150
  • 1,295
  • 1,284
Arian
  • 325
  • 1
  • 15
  • Not exactly. The first constructor is widely used when you need to retrieve only one item or have to avoid a compilation error when assigning the result to a value which is not an array and you are sure the query returns exactly one result. While it may look faster to use the second constructor rather than using an additional .Where() (because you *think* LINQ stops evaluating items in the list after finding the first) it always stops at the first element – usr-local-ΕΨΗΕΛΩΝ Jun 08 '12 at 18:56
-6

linq many ways to implement single simple query on collections, just we write joins in sql, a filter can be applied first or last depending on the need and necessity.

Here is an example where we can find an element with a id in a collection. To add more on this, methods First, FirstOrDefault, would ideally return same when a collection has at least one record. If, however, a collection is okay to be empty. then First will return an exception but FirstOrDefault will return null or default. For instance, int will return 0. Thus usage of such is although said to be personal preference, but its better to use FirstOrDefault to avoid exception handling. here is an example where, we run over a collection of transactionlist

Paolo Forgia
  • 5,804
  • 7
  • 39
  • 55
venkat
  • 141
  • 1
  • 6