Jon*_*Jon 4 c# collections if-statement
我有这个:
if (input.Text.ToUpper() == "STOP")
Run Code Online (Sandbox Code Playgroud)
但是有很多可能的值,我无法像这样单独指定它们:
if (input.Text.ToUpper() == "STOP" || input.Text.ToUpper() == "END")
Run Code Online (Sandbox Code Playgroud)
有没有办法可以做到这样的事情:
if (input.Text.ToUpper() == "STOP", "END", "NO", "YES")
Run Code Online (Sandbox Code Playgroud)
那么使用STOP,END,NO或YES会完成任务吗?
使用任何包含将不起作用,其他时候接受的单词将在其中包含单词STOP和END.
Tim*_*ter 16
您可以使用类似数组的集合Enumerable.Contains:
var words = new[]{ "STOP", "END", "NO", "YES" };
if(words.Contains(input.Text.ToUpper()))
{
// ...
}
Run Code Online (Sandbox Code Playgroud)
字符串扩展的完美情况
将其添加到新文件中
namespace appUtils
{
public static class StringExtensions
{
public static bool In(this string s, params string[] values)
{
return values.Any(x => x.Equals(s));
}
}
}
Run Code Online (Sandbox Code Playgroud)
并以这种方式从您的代码中调用
if(input.Text.In("STOP", "END", "NO", "YES") == true)
// ... do your stuff
Run Code Online (Sandbox Code Playgroud)