字符串.LINQ To SQL查询中的IsNullOrEmpty
本文关键字:IsNullOrEmpty 查询 SQL LINQ To 字符串 | 更新日期: 2023-09-27 18:14:04
我的DBML公开了一个具有可空nvarchar字段的记录集。这个可为空的nvarchar字段在我的c#代码中表示为字符串。
有时这个字段是空的,有时它是一个空字符串,有时它实际上有一个值。
String.IsNullOrEmpty()
在LINQ To SQL工作吗?例如:
var results = from result in context.Records
where String.IsNullOrEmpty(result.Info) == false
select result;
奇怪的是,每个MSDN都支持String.IsNullOrEmpty
(由于它没有被不支持),但我只能找到关于不支持的抱怨。
但是,如果它确实有效,则不应该显式地将其与布尔值进行比较,而是:
var results = from result in context.Records
/*XXX broke :( where !String.IsNullOrEmpty(result.Info) */
where !(result.Info == null || result.Info.Equals(""))
select result;
我不知道这是否有效,但我确信这是可行的:
where (result.Info ?? "") != ""
(强烈建议使用父字符,没有父字符查询生成器可能会混淆)
不支持,因为尝试使用它会导致抛出NotSupportedException
并伴有以下消息:
不支持方法'Boolean IsNullOrEmpty(System.String)'翻译成SQL
相反,您可以使用这种方法来做同样的事情:
var results = from result in context.Records
where result.Info != null && result.Info.Length > 0
select result;
您也可以使用result.Info != String.Empty
来代替检查长度。
除了@ahmad-mageed的答案外,我对所有答案都有问题。
最后使用了更简洁的语法:
where (result.Info ?? "").Length > 0
或
result => (result.Info ?? "").Length > 0
如果使用Linq查询,可以使用函数作为Where方法的参数,例如
var results = context.Records.Where(string.IsNullOrEmpty);
但是在这种情况下,它会给你所有null或空元素,而不是相反。然后为string类创建一个扩展方法(例如string. isnotnullorempty)或执行如下操作:
var results = context.Records.Except(context.Records.Where(string.IsNullOrEmpty));