Latest Post

Friday, 12 May 2017

What is difference between Single() and SingleOrDefault()


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


Single()


It returns a single, specific element of a sequence if element match found. If none or more than one match found for that element in the collection then an exception is thrown.
When to use: If exactly 1 element is expected; not 0 or more than 1.

Examples

Following the Student Entity where we will 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.Single(e => e.StudentId == 1)
Expected Result There is one record where StudentId == 1. It will return this record.
Result
StudentId Firstname Lastname DOB
1 Alok Singh 12/8/1985

Query 2
Student.Single(e => e.Lastname == "Joshi")
Expected Result There are multiple records where Lastname == Joshi. Should fail.
Actual Result InvalidOperationException: Sequence contains more than one element

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

SingleOrDefault()


It returns a single specific element from a collection of elements if there is any match found. If no match is found for that element in the collection, A default value is returned. If there is more than one match found for that element in the collection then an exception is thrown.
When to use: When 0 or 1 elements are expected.

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.SingleOrDefault(e => e.StudentId == 1)
Expected Result There is only one record where StudentId == 1. Should return this record.
Actual Result
StudentId Firstname Lastname DOB
1 Alok Singh 12/8/1985

Query 2
Student.SingleOrDefault(e => e.Lastname == "Joshi")
Expected Result There are multiple records where Lastname == Joshi. Should fail.
Actual Result InvalidOperationException: Sequence contains more than one element

Query 3
Student.SingleOrDefault(e => e.StudentId == 15)
Expected Result There is no record with StudentId = 15. Should return default value.
Actual Result null

Government Jobs