LINQ到对象时,对象为空VS LINQ到SQL对象、为空、LINQ、VS

2023-09-03 05:16:22 作者:不思量自难忘°

我有这样的LINQ to对象查询:

I have this Linq to object query:

var result = Users.Where(u => u.Address.Country.Code == 12)

我得到一个异常,如果地址或国家为空。 为什么此查询不检查地址为空,只是在那之后procced? 这样,我就不用写这个可怕的查询:

I get an exception if the Address or the Country are null. Why this query doesn't check if the address is null and just after that procced? This way I won't need to write this terrible query:

var result = Users.Where(u => u.Address != null &&
                              u.Address.Country != null &&  
                              u.Address.Country.Code == 12)

在LINQ to SQL中的第一个查询wiil做的工作(当然从其他原因)。

In Linq to SQL the first query wiil do the job(from other reasons of course).

时的一个方式,以避免在LINQ的空检查对象?

Is the a way to avoid the "null checks" in linq to object?

推荐答案

不幸的是,空被处理不一致在C#(在许多其他的编程语言)。可空算术的取消的。也就是说,如果你做算术上可空整数,没有任何操作数为空,那么你得到正常的答案,但如果其中任何一个都为空,你会得到空。但成员访问操作符的没有的解除;如果你给一个空操作数的成员访问。运营商,它抛出一个异常,而不是返回空值。

Unfortunately, "null" is treated inconsistently in C# (and in many other programming languages). Nullable arithmetic is lifted. That is, if you do arithmetic on nullable integers, and none of the operands are null, then you get the normal answer, but if any of them are null, you get null. But the "member access" operator is not lifted; if you give a null operand to the member access "." operator, it throws an exception rather than returning a null value.

要是我们从头开始设计一种制度,我们可以说的所有的类型是可空的,那的任意的EX $ P $包含空操作pssion产生空结果不管操作数的类型。因此,调用一个空接收器的方法的或空参数的会产生一个空的结果。该系统使得一大堆的道理,但显然这是远远太晚了我们现在实行什么;千百万code线已被写入了预计当前的行为。

Were we designing a type system from scratch, we might say that all types are nullable, and that any expression that contains a null operand produces a null result regardless of the types of the operands. So calling a method with a null receiver or a null argument would produce a null result. That system makes a whole lot of sense, but obviously it is far too late for us to implement that now; millions upon millions of lines of code have been written that expects the current behaviour.

我们曾经考虑加入解禁成员访问运算符,或许记谱。所以,你可以然后说用户在哪里?地址?国家?code == 12 这将产生一个可空int值,然后可以比较12可空整数通常是。然而,这却从来没有得到过去的是的,这可能是好的,在未来的版本的设计过程的阶段,所以我不会指望它在短期内。

We have considered adding a "lifted" member access operator, perhaps notated .?. So you could then say where user.?Address.?Country.?Code == 12 and that would produce a nullable int that could then be compared to 12 as nullable ints normally are. However, this has never gotten past the "yeah, that might be nice in a future version" stage of the design process so I would not expect it any time soon.