TutuGeorge
TutuGeorge

Reputation: 2022

String comparion against a set of string values

I have a function like this(foo): I need to compare the input string and perform a task accordingly . Task is same, but only for a selected set of values. For all other values do nothing.

function foo(string x)

{
if(x == "abc")
    //do Task1

if(x == "efg")
    //do Task1
if(x == "hij")
    //do Task1
if(x == "lmn")
    //do Task1
}

Is there any other means to do checking other than this? Or putting OR operator inside if?

What is the preferred way?

Upvotes: 3

Views: 202

Answers (4)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726639

There are many ways of doing it. One would be as follows:

var target = new HashSet<string>{ "abc", "efg", "lmn" };
if (target.Contains(x)) {
    ...
}

At max [my list of strings] can grow to 50 strings which is a rare possibility.

Then you should make target a static readonly in your class, like this:

private static readonly StringTargets = new HashSet<string>{ "abc", "efg", "lmn" };

Doing so would ensure that the set is created only once, and is not re-created each time the execution goes through the method that uses it.

Upvotes: 10

Bam4d
Bam4d

Reputation: 610

You can use a switch statement with a default value to catch anything that didn't match

http://blogs.msdn.com/b/brada/archive/2003/08/14/50227.aspx

function foo(string x) {

    switch(x) {

     case "abc":
      //do task 1
     break;

     case "efg":
      //do task 2
     break;

     default:
      //all other cases
     break;
    }
}

Upvotes: -1

Dan Drews
Dan Drews

Reputation: 1976

One way would be to make an array of the acceptable strings, then see if that array contains x

function foo(string x)

{


     string[] strings = new string[] {"abc", "efg", "hij", "lmn"};

     if (strings.contains(x)){
        //do task 1
     }
}

Upvotes: 0

Ehsan
Ehsan

Reputation: 32681

do it like this

function foo(string x)
{
  switch(x)
  {
      case "abc":
      case "efg":
      case "hij":
      case "lmn":
        {
          //do task 1
          break;
        }
      default:
        break;
  }
}

Alternatively you can do this

if(x == "abc"||x == "efg"||x == "hij"||x == "lmn")
   //do Task1

Upvotes: 7

Related Questions