Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In .Net, "most terse" way to check if string is one of multiple values?

Tags:

string

.net

I want to check whether a string matches one of a list of values.

There are of course many, many ways I could go about this: if statement, switch statement, RegEx, etc. However, I would have thought that .Net would have something along the lines of

if (myString.InList("this", "that", "the other thing"))

So far the closest thing I can find would be something like:

"this; that; the other thing;".Contains(myString)

Is that pretty much the only way to go if I want to do the check in a single line and don't want to use RegEx?

like image 885
Rob3C Avatar asked Dec 05 '22 05:12

Rob3C


2 Answers

If you're using .NET 3.0, there's a method of type enumarable objects that would allow this to work on a string array constructed in-line. Does this work for you?

if ((new string[] { "this", "that", "the other thing" }).Contains(myString))

Thanks for the tip comment. Indeed, this also works:

if ((new [] { "this", "that", "the other thing" }).Contains(myString))

I've been ambivalent about whether using inferred types is a good idea. The brevity is nice but other times I get frustrated at trying to figure out the data types of certain variables when the type isn't explicitly stated. Certainly for something as simple as this, though, the type should be obvious.

like image 175
BlueMonkMN Avatar answered Dec 07 '22 18:12

BlueMonkMN


You could use extension methods available in .NET 3.5 to have syntax like

if (myString.InList("this", "that", "the other thing")) {}

Just add something like this (and import it):

public static bool InList(this string text, params string[] listToSearch) {
    foreach (var item in listToSearch) {
        if (string.Compare(item, text, StringComparison.CurrentCulture) == 0) {
            return true;
        }
    }
    return false;
}

If you are using older version, you could still use this function but you will need to call it like:

if (InList(myString, "this", "that", "the other thing")) {}

of course, in InList function, remove this keyword.

like image 37
Josip Medved Avatar answered Dec 07 '22 19:12

Josip Medved