Check if string array contains non-empty strings without loop

I have an If statement that checks the 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, although the Array.Contains method for the first condition would be sufficient to tell me whether the array contains only empty strings, but it gives an InvalidCastException: Conversion from string "" to type Long is not valid , so I assume Not String.Empty actually calculated on what it is trying to convert to long.

Is there a better way I can use to retro-fit this If so that I can enable the test only for empty rows in the array, as part of If, instead of adding a previous loop to test each BaySlots () index for an empty string?

I thought that there probably should be some way to check this, apart from the loop, as it will be a relative amount of work to check if there was any content.

thanks

PS just to clarify this, not to check if the array has zero dimensions or is Nothing, but all the lines that it contains are equal to String.Empty.

+4
source share
1 answer

LINQ 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 is what you prefer.)


Since you have double negation, I suggest replacing it with Enumerable.All for readability:

 If BaySlots.All(Function(x) x = "") OrElse ... 

It also more clearly reflects your intention ("If all entries are empty ...").


Note. In VB.NET, comparing a string with "" or String.Empty also gives True if the string is Nothing .

+4
source

Source: https://habr.com/ru/post/1501462/


All Articles