C#

3 ways to check whether an element is in array in C#

ยท 1 min read
3 ways to check whether an element is in array in C#

In C#, we can check if an element is in an array by using the System.Array class and its IndexOf method. Here's an example:

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
}

The 2nd way is to use FindIndex:

var index = Array.FindIndex(stringArray, x => x == value)

The 3rd way is to 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"));