So I have a conditional that currently looks like this...
if (input.Contains(\",\") || input.Contains(\"/\") || input.Contains(@\"\\\") || input.Contains(\".
How about this?
if(input.IndexOfAny(new char[] { ',', '/', '\\', '.' })>=0)
{
}
You could use some Linq:
if ( ",/\\.".ToCharArray().Any( c => input.Contains( c ) ) )
You could use String.IndexOfAny -- it will scan the string for any one of a set of characters in an array:
if (e.Label.IndexOfAny(new char[]{',', '/', @'\', '.' /* other chars here */}) > -1)
"asdfasdf".ContainsAny(".","/","4");
public static bool ContainsAny(this string stringToCheck, params string[] parameters)
{
return parameters.Any(parameter => stringToCheck.Contains(parameter));
}
An extension method could make things look clean. Have a look at the following.
public static bool ContainsChar(this string input, params char[] characters)
{
foreach (var character in characters)
{
if (input.Contains(character))
{
return true;
}
}
return false;
}
The method's parameters are variadic, so you can add as many chars as you want separated by commas. If you're not comfortable using extension methods, modify to the following:
public static bool ContainsChar(string input, params char[] characters)
{
foreach (var character in characters)
{
if (input.Contains(character))
{
return true;
}
}
return false;
}
Example usage follows:
string myString = "this is my string";
//extension
if (myString.ContainsChar('.', '*', '%')) //do something
//static method
if (ContainsChar(myString, '.', '*', '%')) //do something
Consider using Regex (specify characters you want to check in brackets - remember that some of them must be escaped):
Regex.IsMatch(input, @"[,/]");
or
new[] {",", "/"}.Any(input.Contains)