2

I have string with empty space("________")

string MyNote= Convert.ToString(Session["MyNote"]);

if(MyNote!=null || MyNote != "")
{


}

MyNote != "" does not work if string has more space so

How can I check my string is "" or null by using linq in C#?

1
  • 3
    If you really wanted to use LINQ the correct answer would have been if (MyNote != null && MyNote.Any(c => !char.IsWhitespace(c))) .... But I doubt this is about LINQ. Commented Oct 14, 2013 at 1:01

3 Answers 3

5

String.IsNullOrWhiteSpace is the method you're looking for.

Indicates whether a specified string is null, empty, or consists only of white-space characters.

Alternatively, using your idea:

if(MyNote!=null && MyNote.Trim() != "")
{

}

or

if(MyNote!=null && MyNote.Trim().Length == 0)
{

}
Sign up to request clarification or add additional context in comments.

1 Comment

You should change || into &&. You actually check for Is Not Null Or Not WhiteSpace. This will even throw an exception if MyNote is null.
2
if(MyNote!=null || MyNote.Length > 0) //or you may want to set different value than 0
{


}

1 Comment

And with trimming it won't work either since it throws an exception when MyNote is null.
0

This works for me:

 string MyNote = Session["MyNote"] == null ? String.Empty : Session["MyNote"].ToString();

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.