开发者

Comparing a possibly empty string in C#

I'm trying to compare a string field from a LINQ query on a database using:

e.Comment.equals("Working From Home")

on the WHERE clause.

However, sometimes the Comment field could be empty w开发者_高级运维hich currently causes an Object reference not set to an instance of an object exception.

Is there any way I can check if the Comment isn't empty and THEN compare to avoid the exception?


You can use == instead of Equals:

e.Comment == "Working From Home"

LINQ to SQL will correctly translate this to the appropriate SQL syntax.


In this case, it should be enough to use the '==' operator instead:

e.Comment == "Working From Home"


!String.IsNullOrEmpty(e.Comment) && e.Comment == "Working From Home"


You could do "Working From Home".Equals(e.Comment); or String.Equals(e.Comment, "Working From Home");

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜