1

I want the user to insert a string as a parameter, and afterwards check if that string is equal to one of several strings.

The way I do it now is

....
if(stringParam != "text1" || stringParam != "text2" || stringParam != "text3"...  stringParam != "text10")
....

is there not a way that to write this more readable / pretty? There probably is, but I couldn't figure a way.

Also it doesn't matter if the strings are uppercase or lowercase.

1
  • "one of several strings", are these strings have kind of naming pattern like in your example that contains numeric data? Commented Sep 24, 2019 at 6:03

3 Answers 3

5

You can use a Hashtable, Dictionary or HashSet. You can store in it the strings as keys and then use the method ContainsKey()/Contains() to see if your stringParam matches any of the keys stored previously ("text1", "text2" and so on).

    HashSet<string> mySet = new HashSet<string>(); 


    mySet.Add("text1"); 
    mySet.Add("text2"); 
    mySet.Add("text3"); 
    mySet.Add("text4"); 

    if (mySet.Contains(stringParam)) 
        Console.WriteLine("It matched"); 
Sign up to request clarification or add additional context in comments.

1 Comment

Some of the constructors of a HashSet<T> accept an IEqualityComparer<T>. So to accomodate for "it doesn't matter if the strings are uppercase or lowercase", One could use one of the "IgnoreCase" string comparers like for example: new HashSet<string>(StringComparer.CurrentCultureIgnoreCase).
0

You could use regex matching with a single alternation:

Regex regex = new Regex(@"\b(?:text1|text2|text3|...|text10)\b");
string stringParam = "passes";
Match match = regex.Match(stringParam);
if (!match.Success)
{
    Console.WriteLine("MATCH");
}

Comments

0

You could try this:

// build a string array containing what you want to match.
var myStrings = new [] { "TEXT1", "TEXT2", "TEXT3", ....... };

// search in it
if (myStrings.Contains(stringParam.ToUpper()))
{
    // yes
}

You could also use a HashSet<T>.

But this 'smells' like you're doing something which could be done other ways more efficient, but there is a lack of information for us.


Like Fildor said, you might want to use this one.

// build a string array containing what you want to match.
var myStrings = new [] { "TEXT1", "TEXT2", "TEXT3", ....... };

// search in it
if (myStrings.Any(s => String.Compare(s, stringParam, CultureInfo.InvariantCulture, CompareOptions.IgnoreNonSpace))
{
    // yes
}

3 Comments

Just a sidenote because I ran into it: toUpper doesn't work with turquish "i". Because the Uppercase turquish "i" is not what you get from toUpper...
You probably need to use the myStrings.Any(s => String.Compare(s, stringParam,, CultureInfo.InvariantCulture, CompareOptions.IgnoreNonSpace))
Exactly, just wanted to leave that remark for people trying to use your solution.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.