I just want to know if there's an approach in VB.NET that can find if a specific value exist on a list or something 开发者_JAVA百科which can use in my If-else condition. What I'm doing now is to use this:
If ToStatus = "1CE" Or ToStatus = "2TL" Or ToStatus = "2PM" Then
'Do something
Else
'Do something
End If
This works fine, but how if I have hundreds of string to compare to ToStatus
in the future? It will be a nightmare! Now, if such functionality exists, how can I add "And" and "Or" in the statement?
Thanks in advance!
You can use the Contains
function:
Dim someList = New List(Of String) From { ... }
If Not someList.Contains(ToStatus) Then
You can do the following:
If {"1CE","2TL","2PM"}.Contains(ToStatus) Then
' ...
End If
Like Slaks pointed out, you can use Contains
on an enumerable
collection. But I think readability suffers. I don't care if some list contains my variable; I want to know if my variable is in some list.
You can wrap contains in an extension method like so:
Imports System.Runtime.CompilerServices
Module ExtensionMethods
<Extension()> _
Public Function [In](Of T)(ByVal item As T, ByVal ParamArray range() As T) As Boolean
Return range.Cast(Of T).Contains(item)
End Function
End Module
Then call like this:
If ToStatus.In("1CE","2TL","2PM") Then
you may use select case
select case A
case 5,6,7,8
msgbox "you are in"
case else
msgbox "you are excluded"
end select
For .NET 2.0
I came across another problem where SLaks solution won't work, that is if you use .NET 2.0 where method Contains
is not present. So here's the solution:
If (Array.IndexOf(New String() {"1CE", "2TL", "2PM"}), ToStatus > -1) Then
'Do something if ToStatus is equal to any of the strings
Else
'Do something if ToStatus is not equal to any of the strings
End If
VB.NET - Alternative to Array.Contains?
Remove duplicates from the list
Dim ListWithoutDuplicates As New List(Of String)
For Each item As String In ListWithDuplicates
If ListWithoutDuplicates.Contains(item) Then
' string already in a list - do nothing
Else
ListWithoutDuplicates.Add(item)
End If
Next
精彩评论