Phone Developer
Phone Developer

Reputation: 1461

String.IsNullOrEmpty in LINQ To SQL query?

My DBML exposes a record set that has a nullable nvarchar field. This nullable nvarchar field is represented as a string in my C# code.

Sometimes this field is null, sometimes it is an empty string, and sometimes it actually has a value.

Does String.IsNullOrEmpty() work in LINQ To SQL? For instance, would the following work:

var results = from result in context.Records
              where String.IsNullOrEmpty(result.Info) == false
              select result;

Upvotes: 36

Views: 54997

Answers (5)

Patrick Ribbing
Patrick Ribbing

Reputation: 227

You can use a function as argument to the Where method if you use a Linq query, e.g.

var results = context.Records.Where(string.IsNullOrEmpty);

But in this case that would give you all null or empty elements, instead of the opposite. Then create an extension method to the string class (e.g. string.IsNotNullOrEmpty) or do something like this:

var results = context.Records.Except(context.Records.Where(string.IsNullOrEmpty));

Upvotes: 0

Robert J. Good
Robert J. Good

Reputation: 1357

I had problems with all answers except for @ahmad-mageed's answer.

Ended up using a more concise syntax of:

where (result.Info ?? "").Length > 0

Or

result => (result.Info ?? "").Length > 0

Upvotes: 3

user7116
user7116

Reputation: 64068

Curiously, per MSDN String.IsNullOrEmpty is supported (by virtue of it not being unsupported), yet I can only find complaints about it not being supported.

However, if it does work you should not explicitly compare it to a boolean value, instead:

var results = from result in context.Records
          /*XXX broke :( where !String.IsNullOrEmpty(result.Info) */
          where !(result.Info == null || result.Info.Equals(""))
          select result;

Upvotes: 55

Ahmad Mageed
Ahmad Mageed

Reputation: 96477

It is not supported since attempting to use it results in a NotSupportedException being thrown with this message:

Method 'Boolean IsNullOrEmpty(System.String)' has no supported translation to SQL.

Instead, you can use this approach to do the same thing:

var results = from result in context.Records
              where result.Info != null && result.Info.Length > 0
              select result;

You may also use result.Info != String.Empty instead of checking the length. Both approaches will work.

Upvotes: 12

Amy B
Amy B

Reputation: 110111

I don't know if that works, but I'm sure this does:

where (result.Info ?? "") != ""

(strongly recommend the parens, query generator can get confused without them)

Upvotes: 27

Related Questions