Reputation: 456
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?
Upvotes: 5
Views: 1034
Reputation: 128
hey i was looking for the same thing but in reverse way like my string value should be compared in 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 got the requirement early help can be very useful . so far i have used as below but seeking for advanced help
private static bool LineIsInTheList(List<string> list,string line)
{
foreach (string methodName in list)
{
if (line.Contains(methodName))
return true;
}
return false;
}
Upvotes: 0
Reputation: 3711
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.
Upvotes: 5
Reputation: 25601
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.
Upvotes: 10
Reputation: 25349
You could combine yours and BlueMonks answer and use (assuming .NET 3):
if ("this;that;the other thing;".Split(";").Contains(myString) ...
Upvotes: 1