Latest Post

Friday, 12 May 2017

What is difference between First() vs FirstOrDefault()

Hello readers, I am sharing post about First() vs FirstOrDefault(). Here, you can find  difference between First and FirstOrDefault, When to use and different type of scenario with example.


First()

It returns First element of a sequence or a value from collection of elements. If there are no elements in the result than it will throws InvalidOperationException.
When to use: When more than 1 element is expected and you want only the first .

Examples

Following the Student Enityt where i will to perform query on that.

StudentId Firstname Lastname DOB
1 Alok Singh 12/8/1985
2 Anil Singh 2/19/1984
3 Sachin Kinra 8/30/1996
4 Cris Moris 9/19/1981
5 Sahil Joshi 3/4/1995
6 Rahul Maurya 7/2/1969
7 Raj Joshi 5/29/1984
8 King George 1/9/1980
9 Michel Jonhsan 1/27/1965

Query 1
Student.OrderBy(e => e. DOB)
.First(e => e.Lastname == "Joshi")
Expected Result There are multiple records where Lastname == Joshi. Should return the oldest one.
Actual Result
StudentId Firstname Lastname DOB
7 Raj Joshi 12/8/1985

Query 2
Student.OrderBy(e => e. DOB)
.First(e => e.StudentId == 15)
Expected Result There is no record with StudentId = 15. Should fail.
Actual Result InvalidOperationException: Sequence contains no elements

FirstOrDefault()


It returns the first element of a sequence or default value of underlying type of generic collection. It does not throw InvalidOperationException if no element found.
When to use: When more than 1 element is expected and you want only the first. Also it is fine for the result to be empty.

Examples

Following the Student Enityt where i will to perform query on that.

StudentId Firstname Lastname DOB
1 Alok Singh 12/8/1985
2 Anil Singh 2/19/1984
3 Sachin Kinra 8/30/1996
4 Cris Moris 9/19/1981
5 Sahil Joshi 3/4/1995
6 Rahul Maurya 7/2/1969
7 Raj Joshi 5/29/1984
8 King George 1/9/1980
9 Michel Jonhsan 1/27/1965

Query 1
Student.OrderBy(e => e. DOB)
.FirstOrDefault(e => e.Lastname == "Joshi")
Expected Result There are multiple records where Lastname == Joshi. Should return the oldest one.
Actual Result
StudentId Firstname Lastname DOB
7 Raj Joshi 12/8/1985

Query 2
Student.OrderBy(e => e. DOB)
.FirstOrDefault(e => e.StudentId == 15)
Expected Result There is no record with StudentId = 15. Should return default value.
Actual Result null

Government Jobs