Check if a string start with any character in a list
If your character "list" is definitely going to be a char[]
, I would assume you're best off with:
return toCheck.IndexOfAny(columnChars) == 0;
Disclaimer: I haven't benchmarked this. But that method's just sitting there.
Turn the check around and see if the first character is in the allowable set.
char[] columnChars = new char[] { 'A', 'B', 'C', 'D', 'E' };
private bool startWithColumn(string toCheck)
{
return toCheck != null
&& toCheck.Length > 0
&& columnChars.Any( c => c == toCheck[0] );
}
You can get the first character out of a string easily enough:
char c = toCheck[0];
And then check whether it's in the array:
return columnChars.Contains(c);
I needed something similar, but for strings:
I wanted to know if my string subject
started with any of these strings:
var qualent3s = new string[] { "D", "M", "H", "JUK"};
The LINQ to do so is simple:
qualent3s.Any(x => subject.StartsWith(x))