| Single() vs SingleOrDefault() vs First() vs FirstOrDefault() in LINQ Query
Below are the 3 main difference between Single() vs SingleOrDefault() vs First() vs FirstOrDefault()
Defination
(1)Single():- This will return a single specific element froma sequence
(2)SingleOrDefault():-This will return the single specific element from sequence or will return default value if that element not found
(3)First():-This will return the first element from sequence
(4)FirstOrDefault():- This will returns the first element of a sequence or default value if no element is found
Exception thrown
(1)Single():-It will throws error when 0 or more then 1 elements comes in result
(2)SingleOrDefault():-It will throws error if more then 1 element in result
(3)First():-This will throws error if no elements in the result is return
(4)FirstOrDefault():-If source is null then it will throws error
When to Use
(1)Single():-It will be used when we exactly have 1 element expected and value is not 0 or more then 1
(2)SingleOrDefault():-When we expect 0 or 1 element then we use it
(3)First():-When we expect more then 1 element and we need only first value
(4)FirstOrDefault():-When more then 1 element expected and we need only the first element. It is also okay when result is empty | | |