Reputation: 41
I'm wondering if there's a better way of writing these multiple If statements? I'm sure there is, I just can't figure out what it'd be. In essence the code is just shortening the string.
If text = "-----------------" Then
text = "-"
End If
If text = "----------------" Then
text = "-"
End If
If text = "---------------" Then
text = "-"
End If
If text = "--------------" Then
text = "-"
End If
If text = "-------------" Then
text = "-"
End If
If text = "------------" Then
text = "-"
End If
If text = "-----------" Then
text = "-"
End If
If text = "----------" Then
text = "-"
End If
If text = "---------" Then
text = "-"
End If
If text = "--------" Then
text = "-"
End If
If text = "-------" Then
text = "-"
End If
If text = "------" Then
text = "-"
End If
If text = "-----" Then
text = "-"
End If
If text = "----" Then
text = "-"
End If
If text = "---" Then
text = "-"
End If
If text = "--" Then
text = "-"
End If
Any help is much appreciated.
Upvotes: 2
Views: 701
Reputation: 460238
You could use LINQ:
If text.Length > 0 AndAlso text.All(Function(c) c = "-"c) Then text = "-"
Requested explanation (i found this actually pretty understandable):
Since a string implements IEnumerable(Of Char)
you can use it like a collection of characters. The LINQ extension method Enumerable.All
determines if all items in a sequence/collection match a given predicate(returns True
). In this case the predicate checks whether a given char is "-"c
(the c at the end is necessary with option strict on
to tell the compiler that this is a char and not a string). So only if all chars in the string are minuses this method returns True
. As soon as All
finds a different char it will return False
.
If it returns True
there are 1-n minuses and no other char, so the variable text
can be "-"
.
Upvotes: 5
Reputation: 73
what about?:
Dim maxLengthOfStringYouCompareTo As Integer = 17
Dim xxx As String = ""
Dim text As String = If((xxx.All(Function(charrr) charrr.ToString() = "-") OrElse xxx.Length <= maxLengthOfStringYouCompareTo), "-", "otherValue")
, but if do not need limitation, then remove
xxx.Length <= maxLengthOfStringYouCompareTo
Upvotes: 0