4

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 separately like this:

if (input.Text.ToUpper() == "STOP" || input.Text.ToUpper() == "END")

Is there a way that you can do something like this:

if (input.Text.ToUpper() == "STOP", "END", "NO", "YES")

So that using STOP, END, NO, or YES will do the task?

Using any contains won't work, other times accepted words will have the word STOP and END in them.

Jeroen Vannevel
  • 43,651
  • 22
  • 107
  • 170
Jon
  • 2,566
  • 6
  • 32
  • 52

7 Answers7

16

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

var words = new[]{ "STOP", "END", "NO", "YES" };
if(words.Contains(input.Text.ToUpper()))
{
     // ...      
}
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
5

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
Steve
  • 213,761
  • 22
  • 232
  • 286
4

you can do...

if(new[]{ "STOP", "END", "NO", "YES" }.Contains(input.Text.ToUpper()))
Keith Nicholas
  • 43,549
  • 15
  • 93
  • 156
1

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
}
Styxxy
  • 7,462
  • 3
  • 40
  • 45
0
        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));
GSerjo
  • 4,725
  • 1
  • 36
  • 55
0

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));
CodeLikeBeaker
  • 20,682
  • 14
  • 79
  • 108
0

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"))
burning_LEGION
  • 13,246
  • 8
  • 40
  • 52