26

Is there anyway I can build a Select statement that uses the Contains function? Like this:

Select commentStr
    Case commentStr.Contains("10")
    Case commentStr.Contains("15")
Jon Seigel
  • 12,251
  • 8
  • 58
  • 92
Lou
  • 918
  • 3
  • 16
  • 29

1 Answers1

63
Select Case True
    Case commentStr.Contains("10")
        'foo
    Case commentStr.Contains("15")
        'bar
End Select

Note that with this construct, a maximum of one Case will be executed.

(Also note that your C# friends can't do this with switch, which requires constant expressions in the case clauses :))

AakashM
  • 62,551
  • 17
  • 151
  • 186
  • Perhaps because this syntax is equivalent to a series of `if` s in C# and being able to do the same with a `switch` would be superfluous. In C# `switch` statements are heavily optimized, and therefore only allow constant values. Don't know if it's the same in VB. – Matti Virkkunen Apr 15 '10 at 18:10
  • IMHO this is twisting `Select Case` too far. A series of `If` statements would be more readable, the same amount of code, and (I predict) just as performant. – MarkJ Apr 15 '10 at 19:06
  • @Matti you can twist **any** language and write unreadable code. Using expressions in `Case` statements can be brief **and** readable. The compiler could still detect compile-time constant values and optimise them heavily. – MarkJ Apr 16 '10 at 11:20
  • @MarkJ: And what advantage is there over a bunch of ifs? – Matti Virkkunen Apr 16 '10 at 13:17
  • @MattiVirkkunen: You can write `Case X: CommandA` and it looks organic. – Victor Zakharov Mar 24 '14 at 19:45
  • 3
    @MattiVirkkunen: You can write case condition and case action in a single line, and it looks natural. Writing this in an If/ElseIf looks awkward, or maybe it's just me. – Victor Zakharov Mar 25 '14 at 01:42
  • @MarkJ and @mattivirkkunen Series of `if` is NOT equivalent to `Select Case`. Perhaps you meant one `If - ElseIf -...` statement. In that case (and even for the series of `if`) I strongly disagree about readability; it's even vice versa in favor of `Select Case`. If can contain anything, while `Select Case` is firmly fixed to one variable and you can focus on the cases. The lines are pretty uniform (unlike `if-elseif`), very readable. Finally, it's not the same amount of code, there's extra element and operator at each `ElseIf` line. – Oak_3260548 Sep 22 '21 at 12:39