Cod*_*ace 2 vb.net performance if-statement
我想知道是否有更好的方法来编写这些多个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
If text = "--" Then
text = "-"
End If
Run Code Online (Sandbox Code Playgroud)
任何帮助深表感谢.
您可以使用LINQ:
If text.Length > 0 AndAlso text.All(Function(c) c = "-"c) Then text = "-"
Run Code Online (Sandbox Code Playgroud)
请求的解释(我发现这实际上是可以理解的):
由于字符串实现,IEnumerable(Of Char)您可以像使用字符集一样使用它.LINQ扩展方法Enumerable.All确定序列/集合中的所有项是否与给定谓词匹配(返回True).在这种情况下,谓词检查给定的char是否是"-"c(最后的c是必要的,option strict on告诉编译器这是一个char而不是一个字符串).因此,只有当字符串中的所有字符都是minus时,此方法才会返回True.一旦All找到不同的字符,它就会返回False.
如果它返回True有1-n个缺点而没有其他字符,那么变量text可以是"-".