-1

My question is pretty simple.

Is there a short hand for

if (a == "p" || a == "l" || a == "g" || a == "z")
{
            //do something 
}

Is there an alternate to this. Meaning, Can I just do something like

if (a == ("p" || "l" || "g" || "z"))//this doesn't work

PeeHaa
  • 71,436
  • 58
  • 190
  • 262
user1
  • 1,063
  • 1
  • 8
  • 28

5 Answers5

5
if (new[] { "p", "l", "g", "z" }.Contains(a))

If performance might be a concern, e.g. you have a large list of strings to check, or check it frequently, you should consider storing them in a HashSet<string>, e.g.

var mySet = new HashSet<string> { "p", "l", "g", "z" };
// later...
if (mySet.Contains(a))
Tim S.
  • 55,448
  • 7
  • 96
  • 122
  • 1
    +1. usual reminder - very readable option for short list, consider `HashSet`/`Dictionary` if list is long/frequently used code. – Alexei Levenkov Aug 30 '13 at 19:01
1
Arrays.asList(new String[]{"a","b","c"}).contains("b");
Ashish Thukral
  • 1,445
  • 1
  • 16
  • 26
1

C# code

var myList = new[] { "p", "l", "g", "z" };

if(myList.Contains(a))
{
 //victory :)
}
Johan
  • 8,068
  • 1
  • 33
  • 46
1

You can use switch statement with fall thru:

switch (a) {

  case "p":
  case "l":
  case "g":
  case "z":
    // do something
}
Yuriy Galanter
  • 38,833
  • 15
  • 69
  • 136
1

Better if you write an extension method like:

public static class MyExtension
{
    public static bool In(this string c, params string[] items)
    {
         return items.Contains(c);
         //OR //return items.Any(r => r == c);
    }
}

and then use it like:

if ("a".In("p", "l", "a", "z"))
{
    Console.WriteLine("Exists");
}
else
{
    Console.WriteLine("Doesn't exist");
}
Habib
  • 219,104
  • 29
  • 407
  • 436