Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Question about Switch statement and multiple values

Status
Not open for further replies.

PPettit

IS-IT--Management
Sep 13, 2003
511
US
What's the best alternative for VBScript's SELECT...CASE statement?

Say I've got something like this:
Code:
Select Case strCompany
  Case "Company A","Company B"
    'do something
  Case "Company C"
    'do something else
  Case Else
    'do this if all else fails
End Select

What I'm doing in PS is something like this:
Code:
$array1 = "Company A","Company B"
$array2 = "Company C"
switch ($company)
  {
  {$array1 -contains $_}  <# $_ = whatever is in $company #>
    {<# do this for companies contained in $array1 #>}
  {$array2 -contains $_}
    {<# do this for companies contained in $array2 #>}
  default
    {<# do this is if the company is unspecified #>}
  }

Is this the "right" (or at least the most common) way to handle multiple values?
 
That probably works as well as anything. Because of the way they implemented the switch statement, you can also do this:
Code:
switch ($company)
  {
  "Company A" {<# do this for company A or B #>}
  "Company B" {<# do this for company A or B #>}
  "Company C" {<# do this for company C #>}
  default     {<# do this if the company is unspecified #>}
  }
I don't know if separating out the values would be quicker to evaluate than the -contains or not.
 
It looks like you're trying to say that I could use one option per line (assuming that you mistyped the comments instead of leaving out some code). That should be fine for a small set of data. However, if you're working with a larger set of data and a small number of actions, that seems like it would lead to a lot of repeated code (the action being repeated for multiple options). However, it does seem logical that your method might complete faster since you wouldn't be looking through the arrays every time.
 
I just did the comment that way since you wanted to do the same action whether it was company A or B. And yes, for large sets of data that would not be efficient at all. It's just another consideration.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top