VB.NET If-Else listed

I just want to know if there is an approach in VB.NET that can find if a particular value exists in a list or something that can be used in my If-else condition. Now I have to use this:

If ToStatus = "1CE" Or ToStatus = "2TL" Or ToStatus = "2PM" Then 'Do something Else 'Do something End If 

This works fine, but what if I have hundreds of lines to compare with ToStatus in the future? It will be a nightmare! Now, if such functionality exists, how can I add "A" and "Or" in the instructions?

Thanks in advance!

+8
list if-statement condition
source share
6 answers

You can use the Contains function:

 Dim someList = New List(Of String) From { ... } If Not someList.Contains(ToStatus) Then 
+18
source share

you can use case of choice

 select case A case 5,6,7,8 msgbox "you are in" case else msgbox "you are excluded" end select 
+4
source share

if {"1CE","2TL","2PM"}.Contains(ToStatus)

then ..... End I

+4
source share

Like Specified Slices , you can use Contains in an enumerable collection. But I think that readability suffers. I don't care if the list contains my variable; I want to know if my variable has a list. You can enclose in an extension method, for example:

 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 it:

 If ToStatus.In("1CE","2TL","2PM") Then 
+3
source share

For .NET 2.0

I ran into another problem when the SLaks solution will not work, that is, if you are using .NET 2.0, where the Contains method is missing. So the solution is:

 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 

An alternative to Array.Contains?

0
source share

Remove duplicates from 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 
-one
source share

All Articles