Consider the IEnumerable extension methods SingleOrDefault()
and FirstOrDefault()
MSDN documents that SingleOrDefault:
If your result set returns 0 records:
SingleOrDefault
returns the default value for the type (e.g. default for int is 0)FirstOrDefault
returns the default value for the typeIf you result set returns 1 record:
SingleOrDefault
returns that recordFirstOrDefault
returns that recordIf your result set returns many records:
SingleOrDefault
throws an exceptionFirstOrDefault
returns the first recordConclusion:
If you want an exception to be thrown if the result set contains many records, use SingleOrDefault
.
If you always want 1 record no matter what the result set contains, use FirstOrDefault