Reputation: 32808
I was using the following:
!string.IsNullOrEmpty(Model.ProductID)
But now I need to also check that the string is not equal to "0000". What's the most easy way to do this check?
Upvotes: 4
Views: 249
Reputation: 4294
I think you also need to check if the value is " "
If in C#4.0 , you should use the
!string.IsNullOrWhiteSpace(Model.ProductID) && Model.ProductID != "0000"
Or not ,
!string.IsNullOrEmpty(value) && value.trim().length > 0 && Model.ProductID != "0000"
Upvotes: 0
Reputation: 437396
In addition to the IsNullOrEmpty
check, add a test for string.Trim('0').Length != 0
. This will also catch strings that are any number of zeroes (instead of specifically 4).
Upvotes: 0
Reputation: 244782
How about...
if (!string.IsNullOrEmpty(Model.ProductID) && Model.ProductID.Trim() != "0000")
I really don't think there's a function for your specific case. It's not very often that people want to check a string for all of those three conditions.
And there's no particular reason to worry about "optimizing" this code anyway. The &&
operator is short-circuiting, meaning that the string comparison won't even happen unless the string does contain some value.
Upvotes: 0
Reputation: 62439
if(!string.isNullOrEmpty(Model.ProductID) && Model.ProductID != "0000")
Upvotes: 1
Reputation: 1038890
!string.IsNullOrEmpty(Model.ProductID) && Model.ProductID != "0000"
or write an extension method:
public static class StringExtensions
{
public static bool IsNullEmptyOrZeros(this string value)
{
return !string.IsNullOrEmpty(value) && value != "0000";
}
}
and then:
if (!Model.ProductID.IsNullEmptyOrZeros())
{
...
}
Upvotes: 9