24

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
  • 11,819
  • 8
  • 53
  • 90
Lou
  • 888
  • 3
  • 15
  • 28

1 Answers1

59
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
  • 59,217
  • 16
  • 147
  • 181
  • 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. – Neolisk 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. – Neolisk Mar 25 '14 at 01:42