First()
- Returns first element of a sequence.
- It throw an error when There is no element in the result or source is null.
- you should use it,If more than one element is expected and you want only first element.
FirstOrDefault()
- Returns first element of a sequence, or a default value if no element is found.
- It throws an error Only if the source is null.
- 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...
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: [email protected]
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: [email protected]
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: [email protected]
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: [email protected]
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
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");
Single
andSingleOrDefault
. I hate when people useFirst
when they really meanSingle
; ).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.