Tory Netherton
Tory Netherton

Reputation: 753

What is the simplest way to determine whether or not a one dimensional array of strings contains nothing but zero length strings?

The obvious first thought is:

Public Function CheckStrings(ByVal input As String()) As Boolean
    For Each s As String In input
        If s.Length > 0 Then Return True
    Next
    Return False
End Function

I'm sure there is a simpler way than that though. At least simpler in terms of the code if not necessarily the performance.

End result:

Well, you guys did a pretty good job of simplifying. Well done. I think I'll still use an extension to make it just that much simpler in the main code. The final result really isn't too bad by itself though.

Here's my final code:

<Extension()> _
Public Function AnyNonZero(ByVal value As String()) As Boolean
    If Not value.All(Function(x) String.IsNullOrEmpty(x)) Then Return True
    Return False
End Function

Upvotes: 2

Views: 1574

Answers (3)

Meta-Knight
Meta-Knight

Reputation: 17845

Here's a Linq function similar to Array.TrueForAll:

Dim allEmpty = values.All(Function(x) x.Length = 0)

I find it to be a bit more easily readable than Array.TrueForAll.

Upvotes: 2

Hand-E-Food
Hand-E-Food

Reputation: 12794

You can use this to return true if all elements are zero length.

Dim inputIsEmpty As Boolean = Array.TrueForAll(input, Function(x) x.Length = 0)

Be careful of null references. You may want to use this instead:

Dim inputIsEmpty As Boolean = Array.TrueForAll(input, Function(x) String.IsNullOrEmpty(x))

Upvotes: 3

John
John

Reputation: 1196

How about this? It uses your string array named input.

Array.TrueForAll(input, AddressOf ZeroLengthString)

Private Function ZeroLengthString(ByVal s As String) As Boolean
    Return s.Length = 0
End Function

Upvotes: 2

Related Questions