Linq: Checking if string column has a value (ie. is not null or empty)

ingredient_15939 picture ingredient_15939 · Jul 31, 2012 · Viewed 12.6k times · Source

Not sure if this is the best way to achieve this in Linq.

I'm trying to select Contact records in CRM 2011 where the EMailAddress1 contains a value. The following WHERE clauses I tried both caused exceptions:

Where c.EMailAddress1 > ""

Where Not String.IsNullOrEmpty(c.EMailAddress1)

So I ended up trying this, which seems to work ok:

Where Not c.EMailAddress1.Equals(String.Empty) _
And Not c.EMailAddress1.Equals(Nothing)

But I'm just not certain if this is the most efficient method.. it doesn't seem very elegant. Is there a neater way of checking if a string column has a value?

Answer

Kévin Rapaille picture Kévin Rapaille · Aug 2, 2012

As said here Linq to CRM is really limited. That's why you can't use String.IsNullOrEmpty.

However, you should try to do this :

Where c.EMailAddress1 IsNot Nothing

When a field is empty, it's set to null in the database (never empty). This line should then be enough for your case.

Regards,

Kévin