字符串值不为 null 或为空的 LINQ 语法 [英] LINQ syntax where string value is not null or empty

查看:19
本文介绍了字符串值不为 null 或为空的 LINQ 语法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试进行这样的查询...

I'm trying to do a query like so...

query.Where(x => !string.IsNullOrEmpty(x.PropertyName));

但它失败了...

所以现在我已经实现了以下内容,它有效......

so for now I have implemented the following, which works...

query.Where(x => (x.PropertyName ?? string.Empty) != string.Empty);

LINQ 是否有更好的(更原生的?)方式来处理这个问题?

is there a better (more native?) way that LINQ handles this?

编辑

道歉!不包括提供者...这是使用 LINQ to SQL

apologize! didn't include the provider... This is using LINQ to SQL

推荐答案

http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=367077

问题陈述
可以编写 LINQ to SQL 来获取给定字段中具有 null 或空字符串的所有行,但不能使用 string.IsNullOrEmpty 来执行此操作,即使许多其​​他字符串方法映射到 LINQ to SQL.建议的解决方案允许在 LINQ to SQL where 子句中使用 string.IsNullOrEmpty,以便这两个查询具有相同的结果:

Problem Statement
It's possible to write LINQ to SQL that gets all rows that have either null or an empty string in a given field, but it's not possible to use string.IsNullOrEmpty to do it, even though many other string methods map to LINQ to SQL. Proposed Solution Allow string.IsNullOrEmpty in a LINQ to SQL where clause so that these two queries have the same result:

var fieldNullOrEmpty =
from item in db.SomeTable
where item.SomeField == null || item.SomeField.Equals(string.Empty)
select item;

var fieldNullOrEmpty2 =
from item in db.SomeTable
where string.IsNullOrEmpty(item.SomeField)
select item;

其他阅读:
1. DevArt
2. Dervalp.com
3. StackOverflow 帖子

这篇关于字符串值不为 null 或为空的 LINQ 语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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