Checking if a string array contains a value, and if so, getting its position
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
}
var index = Array.FindIndex(stringArray, x => x == value)
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"));
EDIT: I hadn't noticed you needed the position as well. You can't use IndexOf
directly on a value of an array type, because it's implemented explicitly. However, you can use:
IList<string> arrayAsList = (IList<string>) stringArray;
int index = arrayAsList.IndexOf(value);
if (index != -1)
{
...
}
(This is similar to calling Array.IndexOf
as per Darin's answer - just an alternative approach. It's not clear to me why IList<T>.IndexOf
is implemented explicitly in arrays, but never mind...)