In .Net, the “shortest” way to check if a string is one of several values?

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

There are, of course, many, many ways that I could do this: if statement, switch statement, RegEx, etc. However, I would think that .Net would have something in line with

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

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

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

Is this almost the only way to go if I want to run a single line check and don't want to use RegEx?

+4
source share
4 answers

You can use the extension methods available in .NET 3.5 for 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 an older version, you can still use this function, but you will need to call it like this:

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

Of course, in the InList function, delete this keyword.

+5
source

If you are using .NET 3.0, there is an enumerated object type method that would allow it to work with a string array built in a string. Does this work for you?

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

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

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

I am ambiguous about whether using derived types is a good idea. The brevity is good, but in other cases I get frustrated when trying to figure out the data types of certain variables when the type is not explicitly specified. Of course, for something as simple as this, the type should be obvious.

+10
source

You can combine your answers and use BlueMonks (using .NET 3):

 if ("this;that;the other thing;".Split(";").Contains(myString) ... 
+1
source

Hey, I was looking for the same thing, but vice versa, how should my string value be compared in a list of values

 List<string> methodList = new List<string>(); methodlist.add("this"); methodlist.add("That"); methodlist.add("Everything"); string line = "this is line number 1"; string line2 = "that is line number 2"; string line3 = "about the everything else"; line.contains(methodlist); line2.contains(methodlist); 

Hope you need some early help, which can be very helpful. so far I have used as shown below, but have been looking for additional help.

  private static bool LineIsInTheList(List<string> list,string line) { foreach (string methodName in list) { if (line.Contains(methodName)) return true; } return false; } 
0
source

All Articles