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

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

问题描述

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

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写入SQL,以获取给定字段中具有空字符串或空字符串的所有行,但是即使许多其​​他字符串方法都映射到LINQ到SQL,也无法使用string.IsNullOrEmpty来做到这一点. 拟议的解决方案 在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. StackOverflow帖子

Other Reading:
1. DevArt
2. Dervalp.com
3. StackOverflow Post

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

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