使用If“II”来检查同一查询的多种可能性
这通常是我可以很容易地在网上找到的东西,但我认为我的措辞很难,所以如果这是一个重复的问题,我道歉。
我正在寻找一种更简洁的方法来对同一查询进行IF / OR检查。 例如:
if (sCheck == "string1" || sCheck == "string2" || sCheck == "string3") { MessageBox.Show(sCheck + " is one of the three possible strings."); }
我正在寻找一种更简洁的方式来做同样的If / Or。 我希望这样的东西能起作用但当然不会:
if (sCheck == "string1" || "string2" || "string3") { } if (sCheck == ("string1" || "string2" || "string3")) { }
创建一个包含不同可能性的集合:
if(new[] {"string1", "string2", "string3" }.Contains(sCheck)) { }
您可以创建一个string
集合,然后使用Contains
方法:
List myStrings = new List (){"string1", "string2" , "string3"}; if (myStrings.Contains(sCheck)) { //Do Work }
这可能没什么意义,但在类似的情况下, switch
可能很有用:
switch (sCheck) { case "string1": case "string2": case "string3": MessageBox.Show(sCheck + " is one of the three possible strings."); break; }