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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With