What's the difference between a Sin开发者_StackOverflowgle and a SingleOrDefault ?
Thanks.
The difference is how they treat an empty sequence.
Single
throws an exception if there are no element is found.SingleOrDefault
returns the valuedefault(T)
if no element is found. For reference types and nullables the default value is null. For non-nullable value types it is 0 or similar.
The First
and FirstOrDefault
methods are also related. Here are all four in a table:
method no records multiple records --------------------------------------------- Single exception exception SingleOrDefault default(T) exception First exception first record FirstOrDefault default(T) first record
All these methods also have an overload that takes a predicate.
Another related method is DefaultIfEmpty
which allows you to specify what the default value should be if the sequence is empty, rather than just using the default value for the type.
Single:
Returns the only element of a sequence that satisfies a specified condition, and throws an exception if more than one such element exists.
Single or Default:
Returns the only element of a sequence, or a default value if the sequence is empty; this method throws an exception if there is more than one element in the sequence.
So you can use SingleOrDefault to populate a property/column with a default value if you don't want that property/column to accept NULLs.
Single will throw an Exception if there is anything other than a single result for the query.
SingleOrDefault will only throw an Exception if there are more than one results to your query. If there are no results, you will get back a default value (which is typically null
).
also it's kinda analagous to an outer join in SQL when used in a Linq join.
Single throws a exception if there is more then one result. SingleOrDefault (I am assuming you meant SingleOrDefault not SingleifDefault) will return null if there is more then one result.
精彩评论