views:

383

answers:

1

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")
+3  A: 
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
Great, this works perfectly and made me smack my head and say, "Duh!!!"
Louise
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
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
Just the kind of stuff you'd expect when you let a bunch of VB6 users design a language
Matti Virkkunen
@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
@MarkJ: And what advantage is there over a bunch of ifs?
Matti Virkkunen