C# Linq==null与IsNullOrEmpty——不同还是相同?
在C# Linq==null与IsNullOrEmpty——不同还是相同?,c#,linq,linq-to-sql,C#,Linq,Linq To Sql,在Linq或Linq to Sql中更准确地说:==null和IsNullOrEmpty在以下查询中是否存在差异 From a in context.SomeTable where a.SomeId.Equals(SomeOtherId) && a.SomeOtherColumn == null Select new ..... & 不能在Linq SQL中执行String.IsNullOrEmpty: 方法“Boolean IsNullOrEmpty(System.Strin
Linq
或Linq to Sql
中更准确地说:==null
和IsNullOrEmpty
在以下查询中是否存在差异
From a in context.SomeTable
where a.SomeId.Equals(SomeOtherId)
&& a.SomeOtherColumn == null
Select new .....
&
不能在Linq SQL中执行
String.IsNullOrEmpty
:
方法“Boolean IsNullOrEmpty(System.String)”不受支持
转换为SQL
如果需要,我想您必须在where子句中同时使用null和empty检查:
&& (a.SomeOtherColumn == null || a.SomeOtherColumn == "")
这将在SQL中转换为null和空签入
查看其他答案,使用.Length==0
,将生成SQL来检查varchar列的长度,这可能比检查varchar是否等于'
效率低
编辑:这里有一个堆栈长度溢出,而不是SQL的空检查。看来我猜对了。string.IsNullOrEmpty也适用于空字符串,如
“
最明显的区别在于名称。还检查字符串是否为空。这相当于:
from a in context.SomeTable
where a.SomeId.Equals(SomeOtherId)
&& (a.SomeOtherColumn == null || a.SomeOtherColumn.Length == 0)
...
或
IsNullOrEmpty
等于
s == null || s.Length == 0;
当
s
是string
的实例时,其他答案说明了一个明显的事实,.IsNullOrEmpty()
检查空字符串,同样重要的是要注意比较
where a.SomeOtherColumn == someNullVariable
由于使用SQL空比较而不是C#空比较,将永远不会返回LINQ to SQL中的任何值我不知道LINQ,但是SQL Server会考虑空字符串和NULL作为两个不同的东西(这需要两个不同的命令),而Oracle可能不会。因此,我敢打赌,在某些数据库中,它会有所不同,而在其他数据库中则不会。
s == null || s.Length == 0;
where a.SomeOtherColumn == someNullVariable