In the extension methods Single / SingleOrDefault and First / FirstOrDefault have semantic distinction. Though in many places these methods are being used without the semantic consideration, more often they return the expected results. This behavior makes this misuse more common.
Both the Single and First methods have an accompanying helper method named as xxOrDefault which does nothing more than returning the default value of the specified data type if no element matches the query in the collection. For example if it’s a string collection they return null and if it’s an integer collection they return 0.
So the main semantic distinction comes between Single and First
To check this we create 3 collections like the following.
1:privatestatic List<StudentViewModel> list0;
3:privatestatic List<StudentViewModel> list1 = new List<StudentViewModel>()
The code snippets and the comments describes the functions of the Single and First extension methods and their helping counter parts xxOrDefault.
About the semantic distinction.
If you know that your query should return only one element it’s better to use Single or SingleOrDefault. For example when you query a customer collection by customer ID you know that according to the business there’s only one customer ID with a specific value. First or FirstOrDefault could be used in the scenario but it doesn’t give you the semantics of the business logic.
And Single or SingleOrDefault throws an InvalidOperationException with the message ‘sequence contains more than one element’ if the collection has more than one element matching the query. This behavior sometimes can be used to validate.
Another common misuse of the above extension methods is chaining them unnecessarily with ‘where’ statement like this
1:// this is a common misuse
2: list1.Where(e => e.StudentId == 7).Single();
4: list1.Single(e => e.StudentId == 7);
If you want the code for the demonstration purpose you can download it here