3

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?

10
  • 4
    The switch statement is a good fit for such cases; it allows you to write the target values nicely separated and with a minimum of unnecessary boilerplate. Commented Aug 5, 2013 at 13:34
  • A switch statement doesn't really make much of a difference here IMO. Commented Aug 5, 2013 at 13:35
  • 1
    Some people are partial to if (new[] {"abc", "efg", "hij", "lmn"}.Contains(x)) { Task1(); }... Not sure myself, but it works. Commented Aug 5, 2013 at 13:39
  • 1
    @anaximander Good one. But it is interesting that string[] does not actually contain a method Contains, so that works only because of Linq. Not that that is a problem. The pure array solution would be if (Array.IndexOf(new[] {"abc", "efg", "hij", "lmn"}, x) != -1) { ... }, but that looks quite awful. Commented Aug 5, 2013 at 13:51
  • 1
    Are you just looking for some nice in-line syntax? If so, you can always make an extension method that gives you syntax like if(x.Is("abc", "efg", "hij", "lmn")) { } Commented Aug 5, 2013 at 13:55

4 Answers 4

10

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.

Sign up to request clarification or add additional context in comments.

11 Comments

+1 I'd say this is a better alternative to the if than the switch, with the switch you are still pretty much writing the same amount of code.
Agreed, also depending on the amount of comparison entries you are putting in there it could be faster to go with a List VS a hashset, but as your list of comparisons grows I think hashset offers better performance. see this post here. stackoverflow.com/questions/150750/hashset-vs-list-performance
I think the nicest thing about this is that it lets you easily move target into some class or provider and do if(BusinessRulesFooClass.Something(x)). In fact, depending on the scenario it's possible it should have been like that all along...
@NOOB You should still get about three times speed improvement with ten strings. Making it static ensures that the set object is not re-created each time the code goes through the method. Making it readonly is a way to show to the readers of your code that you are not planning to replace the instance of the set after initialization. This enables additional optimizations in the compiler.
@NOOB What error do you get? As any static variable, it needs to be defined outside of the method, and its declaration may not use var. Copy-paste the second code snippet from the answer outside your method, and it should work. I assume that you have using System.Collections.Generic; at the top of your file, too.
|
7

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

2 Comments

Implementation of switch case in this fashion might be a better solution for me i think.
Will this cause the comparsion operation to be done against all the cases? Rather than do the task on finding the first occurence.
0

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
     }
}

Comments

-1

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;
    }
}

2 Comments

He wants to perform the same task not different tasks (Task1 on all of them, not task 1 on one and task 2 on the other)
Answer is in right direction, but formatted wrong...probably misunderstood the question...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.