I have this string array:
string[] stringArray = { \"text1\", \"text2\", \"text3\", \"text4\" };
string value = \"text3\";
I would like to
IMO the best way to check if an array contains a given value is to use System.Collections.Generic.IList
method the following way:
((IList)stringArray).Contains(value)
Complete code sample:
string[] stringArray = { "text1", "text2", "text3", "text4" };
string value = "text3";
if (((IList)stringArray).Contains(value)) Console.WriteLine("The array contains "+value);
else Console.WriteLine("The given string was not found in array.");
T[]
arrays privately implement a few methods of List
, such as Count and Contains. Because it's an explicit (private) implementation, you won't be able to use these methods without casting the array first. This doesn't only work for strings - you can use this trick to check if an array of any type contains any element, as long as the element's class implements IComparable.
Keep in mind not all IList
methods work this way. Trying to use IList
's Add method on an array will fail.