How can I compare multiple variables to a single condition?

后端 未结 7 728
时光取名叫无心
时光取名叫无心 2020-12-19 16:06

I have this:

if (input.Text.ToUpper() == \"STOP\")

But there are so many possible values that I wouldn\'t be able to specify them all sepa

相关标签:
7条回答
  • 2020-12-19 16:20

    You can hold an array of the possible words and match it with the Contains method:

    string[] validInput = new string[] { "STOP", "END", "NO", "YES" };
    
    // input is the input you have
    if (validInput.Contains(input.Text.ToUpper()))
    {
        // Do something
    }
    
    0 讨论(0)
  • 2020-12-19 16:27
            var tasks = new List<string> { "STOP", "END", "NO", "YES" };
            tasks.Contains(input.Text.ToUpper());
    

    looks better

            var tasks = new List<string> { "stop", "end", "no", "yes" };
            tasks.Exists(x => string.Equals(x, input.Text, StringComparison.OrdinalIgnoreCase));
    
    0 讨论(0)
  • 2020-12-19 16:33

    You could use LINQ to do this. That way if you have both STOP and END in your string, it will pick up on both of them:

    var myStringArray= new[]{ "STOP", "END", "NO", "YES" };
    var query = myString.Any(x => myStringArray.Contains(x));
    
    0 讨论(0)
  • 2020-12-19 16:35

    Perfect situation for a string extension

    Add this to a new file

    namespace appUtils
    {
        public static class StringExtensions
        {
            public static bool In(this string s, params string[] values)
            {
                return values.Any(x => x.Equals(s));
            }
        }
    }
    

    and call from your code in this way

    if(input.Text.In("STOP", "END", "NO", "YES") == true)
       // ... do your stuff
    
    0 讨论(0)
  • 2020-12-19 16:39

    create extension:

    public static class Extension
    {
        public static bool EqualsAny(this string item, params string[] array)
        {
            return array.Any(s => item.ToUpper() == s.ToUpper());
        }
    }
    

    using:

    if (inputText.EqualsAny("STOP", "END", "NO", "YES"))
    
    0 讨论(0)
  • 2020-12-19 16:40

    You could use a collection like array and Enumerable.Contains:

    var words = new[]{ "STOP", "END", "NO", "YES" };
    if(words.Contains(input.Text.ToUpper()))
    {
         // ...      
    }
    
    0 讨论(0)
提交回复
热议问题