Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VB.NET If-Else in List

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 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!

like image 587
dpp Avatar asked Jul 18 '11 01:07

dpp


People also ask

What is the use of if if else in VB net?

If the Boolean expression evaluates to true, then the if block of code will be executed, otherwise else block of code will be executed.

What is if/then else statement in Visual Basic?

Else statement is encountered, condition is tested. If condition is True , the statements following Then are executed. If condition is False , each ElseIf statement (if there are any) is evaluated in order. When a True elseifcondition is found, the statements immediately following the associated ElseIf are executed.


1 Answers

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
like image 179
KyleMit Avatar answered Oct 18 '22 22:10

KyleMit