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.
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);
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.
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...)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With