Fastest way to compare a string with an array of strings in C#2.0
What kind of comparison do you want? Do you want to know if the given string is in the array?
bool targetStringInArray = array.Contains(targetString);
do you want an array of comparison values (positive, negative, zero)?
var comparisons = array.Select(x => targetString.CompareTo(x));
If you're checking for containment (i.e. the first option) and you're going to do this with multiple strings, it would probably be better to build a HashSet<string>
from the array:
var stringSet = new HashSet<string>(array);if (stringSet.Contains(firstString)) ...if (stringSet.Contains(secondString)) ...if (stringSet.Contains(thirdString)) ...if (stringSet.Contains(fourthString)) ...
You mean to see if the string is in the array? I can't remember if arrays support the .Contains() method, so if not, create a List< string >, add your array to the list via AddRange(), then call list.Contains({string to compare}). Will return a boolean value indicating whether or not the string is in the array.
If you are doing this many times with a single array, you should sort the array and binary search it:
Array.Sort(array);int index = Array.BinarySearch(array, input);// if (index < 0) // does not exists, "items > ~index" are larger and "< ~index" are smaller// otherwise, "items > index" are larger and "< index" are smaller.
Otherwise just check the whole array naively:
bool exists = Array.IndexOf(array, input) >= 0;