Linq == null vs IsNullOrEmpty -- 不同或相同

本文关键字:IsNullOrEmpty null vs Linq | 更新日期: 2023-09-27 18:31:46

更准确地说LinqLinq to Sql:以下查询中的== nullIsNullOrEmpty之间有区别吗?

From a in context.SomeTable
where a.SomeId.Equals(SomeOtherId)
&& a.SomeOtherColumn == null
Select new .....

&

From a in context.SomeTable
where a.SomeId.Equals(SomeOtherId)
&& string.IsNullOrEmpty(a.SomeOtherColumn)
Select new .....

Linq == null vs IsNullOrEmpty -- 不同或相同

你不能在 Linq-SQL 中执行String.IsNullOrEmpty

方法"布尔值是空或空(系统字符串)"不支持 转换为 SQL。

如果你需要它,我想你必须在你的 where 子句中同时进行空和空检查:

&& (a.SomeOtherColumn == null || a.SomeOtherColumn == "")

这将转换为 SQL 中的空和空检查。

查看其他答案,使用 .Length == 0 将生成 SQL 来检查 varchar 列的长度,这可能不如检查 varchar 是否等于 '' 的效率。

编辑:这是SQL的长度与空检查的堆栈溢出答案。看来我猜对了。

字符串。IsNullOrEmpty 也适用于空字符串,如 ""

最明显的区别在于名称。 IsNullOrEmpty还会检查字符串是否为空。它相当于:

from a in context.SomeTable
where a.SomeId.Equals(SomeOtherId)
&& (a.SomeOtherColumn == null || a.SomeOtherColumn.Length == 0)
...

from a in context.SomeTable
where a.SomeId.Equals(SomeOtherId)
&& (a.SomeOtherColumn == null || a.SomeOtherColumn == "")
...

虽然其他答案已经陈述了.IsNullOrEmpty()检查空字符串的明显事实,但同样重要的是要注意比较

where a.SomeOtherColumn == someNullVariable

永远不会在 LINQ to-SQL 中返回任何值,因为使用的是 SQL 空值比较而不是 C# 空值比较。 这实际上是 LINQ-to-SQL 中的一个错误。

IsNullOrEmpty等于

s == null || s.Length == 0;

其中sstring的实例