Search code examples
linqlinq-to-sql

LINQ syntax where string value is not null or empty


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


Solution

  • 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