36

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;
2

5 Answers 5

55

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;
Sign up to request clarification or add additional context in comments.

1 Comment

That didn't worked for me. Profiler showed only check for empty string, but not for null value.
27

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)

2 Comments

I like this one, but I guess much like String.IsNullOrEmpty being not supported without documentation to that effect the null coalesce operator is supported without documentation! Oy.
Worked for me, but is this style of coding OK?
12

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.

Comments

3

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

Comments

0

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));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.