LINQ:
Is it more efficient to use the Single() operator over First() when ever I know for certain that the query will return a single record?
Is there a difference?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
If you’re expecting a Single record, it’s always good to be explicit in your code.
I know others have written why you use one or the other, but I thought I’d illustrate why you should NOT use one, when you mean the other.
Note: In my code, I will typically use
FirstOrDefault()andSingleOrDefault()but that’s a different question.Take, for example, a table that stores
Customersin different languages using a Composite Key (ID,Lang):This code above introduces a possible logic error ( difficult to trace ). It will return more than one record ( assuming you have the customer record in multiple languages ) but it will always return only the first one… which may work sometimes… but not others. It’s unpredictable.
Since your intent is to return a Single
CustomeruseSingle();The following would throw an exception ( which is what you want in this case ):
Then, you simply hit yourself on the forehead and say to yourself… OOPS! I forgot the language field! Following is the correct version:
First()is useful in the following scenario:It will return ONE object, and since you’re using sorting, it will be the most recent record that is returned.
Using
Single()when you feel it should explicitly always return 1 record will help you avoid logic errors.