0

How to write an If Condition having a single variable but multiple values.

Ex : 'Consider I have employee details filled in a data table

If (dt.Rows(0).Items("Id").ToString() = "548" Or dt.Rows(0).Items("Id").ToString() = "78787" Or dt.Rows(0).Items("Id").ToString() = "787" Or dt.Rows(0).Items("Id").ToString() = "11" Or dt.Rows(0).Items("Id").ToString() = "025" Or dt.Rows(0).Items("Id").ToString() = "568") Then
MessageBox.Show("INSIDE")
End if

How can I optimize this If condition?

3
  • What type is dt? Commented May 16, 2021 at 15:20
  • OrElse will short circuit the If Commented May 16, 2021 at 18:45
  • What data type is the Id column? I would guess Integer. In that case, one thing you could do is treat the values as Integers. NEVER convert data that is not text to Strings unless you have to. In this case, CInt(dt.Rows(0)("Id")) = 548 or dt.Rows(0).Field(Of Integer)("Id") = 548 would be a start. Commented May 17, 2021 at 0:18

1 Answer 1

1

You can use a Select statement with multiple items in one case:

Select dt.Rows(0).Items("Id").ToString()
Case "548", "78787", "787", "11", "025", "568"
    MessageBox.Show("INSIDE")
End Select
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.