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);
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()
is that First()
returns the element itself, while Take()
returns a sequence of elements that contains exactly one element. (If you pass 1 as the parameter).
.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.
.FirstOrDefault
will return null for reference types. I was confused about what a "default" object would be. This answer cleared that up. - Mike Taverne
.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.
First()
FirstOrDefault()
We have an UserInfos table, which have some records as shown below. On the basis of this table below I have created example...
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()
.
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
.
First:
FirstOrDefault:
From: http://www.technicaloverload.com/linq-single-vs-singleordefault-vs-first-vs-firstordefault/
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));
}
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.
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.
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.
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);
}));
This type of the function belongs to element operators. Some useful element operators are defined below.
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();
Sorry for posting answer to old post. detail and good explanation so please read below urls http://www.technicaloverload.com/linq-single-vs-singleordefault-vs-first-vs-firstordefault/
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.
.First
and.FirstOrDefault
both take predicates as arguments, sovar result = List.Where(x => x == "foo").First();
could be rewritten asvar result = List.First(x => x == "foo");
- Rian SchmitsSingle
andSingleOrDefault
. I hate when people useFirst
when they really meanSingle
; ) - BartoszKP