linq-to-sql SingleOrDefault为null时返回 [英] linq-to-sql SingleOrDefault return when null

查看:123
本文介绍了linq-to-sql SingleOrDefault为null时返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个linq-to-sql查询,并且正在从表中加载一个ID(数据库中的bigint和我的代码中的long),如下所示:

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();

当我得到结果时,我使用SingleOrDefault,以防返回值为空.这是否意味着如果结果为空,则SomeQuery变量将为0还是null?

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?

谢谢.

推荐答案

如果您查看

返回序列的唯一元素,如果返回则返回默认值 序列为空;如果还有更多,此方法将引发异常 而不是序列中的一个元素.

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.

明确指出,如果序列为空,它将返回默认值,长期以来,bigint为 0 . 为什么在下面解释

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

默认关键字状态的

在通用类和方法中,出现的一个问题是如何分配 如果您不知道默认值,则为参数化类型T的默认值 预先进行以下操作:

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:

T是引用类型还是值类型.

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

如果T是值类型,则它是数字值还是结构.

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

给出参数化类型T的变量t,则语句t = null 仅当T为引用类型且t = 0仅对以下项有效时才有效 数值类型,但不适用于结构.解决方案是使用 默认关键字,对于引用类型,该关键字将返回null,而 用于数值类型.

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.

这篇关于linq-to-sql SingleOrDefault为null时返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆