OneBite.Dev - Coding blog in a bite size

Search For A Specific Element In An Array In C#

Code snippet for how to Search For A Specific Element In An Array In C# with sample and detail explanation

Working with arrays is an essential aspect of programming. In C#, the process of searching for a specific element within an array can be achieved using various methods, such as the Array.IndexOf, Array.Find, or Array.Exists methods.

Code snippet: Using Array.IndexOf to search for an element

Before heading into the explanation, let’s look at a simple code snippet that demonstrates the application of Array.IndexOf method.

using System;

class Program
{
    static void Main()
    {
        string[] array = {"Apple", "Banana", "Cherry", "Date", "Elderberry"};
        int index = Array.IndexOf(array, "Cherry");
        Console.WriteLine(index);
    }
}

Code Explanation for ‘Using Array.IndexOf to search for an element’

In the provided code snippet, we start by declaring and initializing a string array containing five elements.

string[] array = {"Apple", "Banana", "Cherry", "Date", "Elderberry"};

Next, we use the Array.IndexOf method to search for the string “Cherry” in our array. This method requires two parameters: the array to search in and the element to search for. It returns the index of the first occurrence of the specified element in the array. If the element is not found, it returns -1.

int index = Array.IndexOf(array, "Cherry");

Lastly, we simply print out the returned index.

Console.WriteLine(index);

When this code runs, the output is 2, which is the index position of “Cherry” in our array. Always remember that array indexing in C# starts from 0, so the index of the first element is 0, the second element is 1, and so on.

That’s it! This is a simple way of searching for a specific element in an array in C#. Always keep in mind that the Array.IndexOf method is case-sensitive, so it is essential to consider letter casing when searching for a string.

c-sharp