linq-to-sql SingleOrDefault return when null

2019-09-09 09:56发布

问题:

I'm writing a linq-to-sql query and I'm loading an ID (a bigint in the database and a long in my code) from a table, something like this:

var SomeQuery = (from x in ...
                 select x.ID).SingleOrDefault();

When I get the result, I use SingleOrDefault in case the return is empty. Does that mean that if the result is empty the SomeQuery variable will be 0 or null?

Thanks.

回答1:

If you look the documenation for SingleOrDefault

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.

It cleary states that if the sequence is empty it will return the default value which for long and bigint is 0. Why explained below

Documenation for default keyword states

In generic classes and methods, one issue that arises is how to assign a default value to a parameterized type T when you do not know the following in advance:

Whether T will be a reference type or a value type.

If T is a value type, whether it will be a numeric value or a struct.

Given a variable t of a parameterized type T, the statement t = null is only valid if T is a reference type and t = 0 will only work for numeric value types but not for structs. The solution is to use the default keyword, which will return null for reference types and zero for numeric value types.



回答2:

Default is returned if no element found.(default value of int is 0)

Value is returned if one is found.

Exception is thrown if more than one is found.