Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if a string array contains a value, and if so, getting its position

Tags:

arrays

string

c#

People also ask

How do you check if a position in an array exists?

To check if an array index exists, access the array at the specific index and check if the result is not equal to undefined . If the result is not equal to undefined the array index exists.

How do I determine whether an array contains a particular value in C#?

Exists(T[], Predicate<T>) Method is used to check whether the specified array contains elements that match the conditions defined by the specified predicate. Syntax: public static bool Exists<T> (T[] array, Predicate<T> match);

How do you check if an array has a value?

For primitive values, use the array. includes() method to check if an array contains a value. For objects, use the isEqual() helper function to compare objects and array. some() method to check if the array contains the object.

How do you check if an element is an array of strings?

To check if all elements in array are strings with JavaScript, we can use the array every method and the typeof operator. to define the check function that calls arr. every with a callback that checks of each entry i is a string with typeof .


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...)