开发者

Can I have an if statement like this? If Test = "test1" or "test2" or "test3" without going the long way?

Do i have to set my if statement as

if(Test == "test1" || Test == "test2" || Test == "test3")
{
    //do something
}
开发者_运维技巧

Is there a way to have something like

if(Test == "test1":"test2":"test3")


Yes.

if (new [] { "test1", "test2", "test3" }.Contains(Test))

You can even write an extension method:

public static bool IsAnyOf<T>(this T obj, params T[] values) { 
    return values.Contains(T); 
}

if (Test.IsAnyOf("test1", "test2", "test3"))

For optimal performance, you can make overloads that take two or three parameters and don't use arrays.


There is nothing wrong with the code that you have written. It is easy to understand, but you could try:

switch (Test)
{
   case "test1":
   case "test2":
   case "test3":
      //your code here
      break;
   default :
      //else code
      break;
 }

As you can see, this considerably more verbose than your original if statement and not immediately obvious what it is for, but it is an answer of sorts. And it will compile to quite efficient intermediate code. In fact, if this post is to be believed, then it could compile to more efficient code than the if statement in your post, depending on whether the values are considered "adjacent" by the compiler.


What you could do to shorten your statement a little is the following:

if (new[] { "test1", "test2", "test2" }.Contains(Test))
{
    ...
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜