Reputation: 10144
I have an If statement that checks a number of things (BaySlots() is an array of strings).
If (Not BaySlots.Contains(Not String.Empty)) OrElse
(Not BayAcId = 0 AndAlso Not BayAcId = acProgramId _
AndAlso overrideSetting = False) Then
I though the Array.Contains
method of the first condition would be sufficient to tell me if the array held only empty strings, but it gives InvalidCastException: Conversion from string "" to type Long is not valid
so I'm guessing Not String.Empty
is actually evaluated to something that is attempted to be converted to a Long.
Is there a better method I can use to retro-fit this If, so that I can still include the test for only empty strings in the array, as part of the If, rather than having to add a preceding loop to test each index of BaySlots() for an empty string?
I thought there should probably be some way of testing this other than looping as that would be a relative lot of work just to test if there was no content.
Thanks
PS just to clarify this is not to test if the array has zero dimensions or is equal to Nothing but that the strings it does contain are all equal to String.Empty.
Upvotes: 4
Views: 2130
Reputation: 172220
LINQ's Enumerable.Any
can do this. A direct translation of your Not Contains(Not String.Empty))
would be:
If (Not BaySlots.Any(Function(x) x <> "")) OrElse ...
(Feel free to replace ""
with String.Empty
, if that's what you prefer.)
Since you have a double negation here, I suggest to replace it with Enumerable.All
for readability:
If BaySlots.All(Function(x) x = "") OrElse ...
This also communicates your intent more clearly ("If all entries are empty...").
Note: In VB.NET, comparing a string to ""
or String.Empty
also yields True
if the string is Nothing
.
Upvotes: 4