LINQ syntax where string value is not null or empty

Jon Erickson picture Jon Erickson · Sep 2, 2009 · Viewed 119.2k times · Source

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

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

but it fails...

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

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

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

EDIT

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

Answer

RSolberg picture RSolberg · Sep 2, 2009

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

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;

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