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<T>.Contains(T item)
method the following way:
((IList<string>)stringArray).Contains(value)
Complete code sample:
string[] stringArray = { "text1", "text2", "text3", "text4" };
string value = "text3";
if (((IList<string>)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<T>
, 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<T>
methods work this way. Trying to use IList<T>
's Add method on an array will fail.
You could use the Array.IndexOf method:
string[] stringArray = { "text1", "text2", "text3", "text4" };
string value = "text3";
int pos = Array.IndexOf(stringArray, value);
if (pos > -1)
{
// the array contains the string and the pos variable
// will have its position in the array
}
You can use Array.IndexOf()
- note that it will return -1 if the element has not been found and you have to handle this case.
int index = Array.IndexOf(stringArray, value);
The simplest and shorter method would be the following.
string[] stringArray = { "text1", "text2", "text3", "text4" };
string value = "text3";
if(stringArray.Contains(value))
{
// Do something if the value is available in Array.
}
You can try this, it looks up for the index containing this element, and it sets the index number as the int, then it checks if the int is greater then -1, so if it's 0 or more, then it means it found such an index - as arrays are 0 based.
string[] Selection = {"First", "Second", "Third", "Fourth"};
string Valid = "Third"; // You can change this to a Console.ReadLine() to
//use user input
int temp = Array.IndexOf(Selection, Valid); // it gets the index of 'Valid',
// in our case it's "Third"
if (temp > -1)
Console.WriteLine("Valid selection");
}
else
{
Console.WriteLine("Not a valid selection");
}
We can also use Exists
:
string[] array = { "cat", "dog", "perl" };
// Use Array.Exists in different ways.
bool a = Array.Exists(array, element => element == "perl");
bool c = Array.Exists(array, element => element.StartsWith("d"));
bool d = Array.Exists(array, element => element.StartsWith("x"));