How to check if an array contains a specific element in C#

Introduction 

 in this article, you can check if an array contains a specific element using the contents method of the System.Linq namespace. An array is a collection of elements of the same type stored in contiguous memory locations. Sometimes, you may need to check whether an array contains a specific element.

To check whether an array contains a specific element in C#, you can use the Contains method, which is part of the LINQ (Language Integrated Query) extension methods for the Enumerable interface. The Contains method returns a Boolean value indicating whether the specified element is present in the Array.

Here's the syntax for using the Contains method 

Here's an example  

public class Program
{
    static void Main(string[] args)
    {
        // Create an array of integers
        int[] numbers = { 2, 3, 4, 5, 6 };

        // check if the array contains the number 3
        bool containsfour = numbers.Contains(4);

        //Print the result
        Console.WriteLine("The array contains 3: " + containsfour);
    }
}

In this statement, the Contains method is called on the numbers array, passing in the number 4 as the argument. The method returns a boolean value indicating whether the Array contains the specified element.

Note. that you need to include the System.Linq namespace at the top of your file in order to use the Contains method. An array is a collection of elements of the same type stored in contiguous memory locations. Each element in an array can be accessed using an index that starts at 0 for the first element and increments by 1 for each subsequent element. You can find a specific element in an array using various methods. Here are four common ways to do so in C#

  1. Using the IndexOf method. 
  2. What is the specific element of an array?  
  3. Using the Contains method.
  4. Using Existing value 

Method 1. Using the IndexOf.

The Array.IndexOf method searches for a specific element in an array and returns its index position. Here is an example of how to use it 

int[] num = { 1, 2, 3, 4, 5 };
int index = Array.IndexOf(num, 3); //returns the index of the first occurrence of 3 in the array

 This example has an integer array called numbers with five elements. We want to find the element's index with the value of 3. To do this, we call the Array.IndexOf method and pass in the Array as the first argument and the value we are searching for as the second argument. The method will return the index of the first occurrence of the value in the Array. In this case, the index variable will be set to 2 because three is at the third position in the Array.

If the value is not found in the Array, the Array.IndexOf method will return -1. For example 

int[] num = { 1, 2, 3, 4, 5 };
int index = Array.IndexOf(num, 6); // returns -1

In this statement, the value 6 is not present in the Array, so the Array.IndexOf method will return -1.  

   static void Main(string[] args)
        {
            // Create an array of integers
            int[] numbers = { 20, 30, 40, 40, 50 };

            // Find the index of the value 40
            int index = Array.IndexOf(numbers, 40);

            // Check if the value was found
            if (index >= 0)
            {
                Console.WriteLine("The value 40 was found at index " + index);
            }
            else
            {
                Console.WriteLine("The value 40 was not found in the array");
            }

            // Find the index of the value 60 (which is not in the array)
            index = Array.IndexOf(numbers, 60);

            // Check if the value was found
            if (index >= 0)
            {
                Console.WriteLine("The value 60 was found at index " + index);
            }
            else
            {
                Console.WriteLine("The value 60 was not found in the array");
            }

            Console.ReadLine();
        }
    }

In this, we create an array of integers and use the Array.IndexOf method to find the index of the value 30. We then check if the value was found and print a message to the Console.

We also use the Array.IndexOf method to find the index of the value 60, which is not in the Array. In this case, the method returns -1, so we print a different message to the Console.

The output of this program would be 

Method 2. What is the specific element of an array?  

In this statement, the specific element of an array is accessed using the index of the element within square brackets following the array variable name. For example, if you have an integer array named myArr, and you want to access the third element of the Array, you would write 

int[] myArr = {1, 2, 3, 4, 5};
int thirdElement = myArr[2];

In this example, myArr[2] accesses the third element of the myArray (remember that arrays in C# are zero-indexed, so the first element of the Array has an index of 0). The value of the third element (3) is then assigned to the third element variable. 

 public static void Main()
    {
        int[] myArr = { 10, 20, 30, 40, 50 };

        // Access the third element of the array
        int thirdElement = myArr[2];

        // Print the value of the third element to the console
        Console.WriteLine("The value of the third element is: " + thirdElement);
    }
}

This program declares an integer array called myArr with five elements. We then access the third element of the Array (which has an index of 2 since arrays in C# are zero-indexed) using the [] operator and assign it to a variable called thirdElement. Finally, we print the value of thirdElement to the Console using Console.WriteLine(). When you run this program, you should see the following output 

Output

 

Method 3. Using the Contains method

In this program, you can use the Contains method to check if an array has a specified element. The Contains method returns a boolean value indicating whether the specified element exists in the Array.

Here is an example of how to use the Contains method in C# 

 public class Program
    {
            static void Main(string[] args)
            {
            int[] numbers = { 1, 2, 3, 4, 5 };

            if (numbers.Contains(4))
            {
                Console.WriteLine("The array contains the number 4");
            }
            else
            {
                Console.WriteLine("The array does not contain the number 4");
            }
        }
     }

In this statement, the Contains method is used to check if the numbers The Array contains the number 3. If it does, the program will output The Array with 4. Otherwise, it will output The Array does not have the number 4.

Output 

Method 4. Using Existing value

If the element is present in the Array, Array.Exists() returns true, else it returns false. To tell if a value exists in an array in C#, you can use the Array.IndexOf method. This method returns the index of the first occurrence of a specified value in the Array or -1 if the value is not found. Here is an example

public static void Main(string[] args)
        {
                string[] StateDetails = { "Noida", "Naagpur",
                "Mumbhai", "Delhi", "Faridabad",
                "Rohtak", "Lukhnow", "Banglore" };

                Console.WriteLine("One or more states begin with 'N': {0}",
                    Array.Exists(StateDetails, element => element.StartsWith("N")));

                Console.WriteLine("One or more states begin with 'B': {0}",
                    Array.Exists(StateDetails, element => element.StartsWith("B")));

                Console.WriteLine("Is sameCity one of the State? {0}",
                    Array.Exists(StateDetails, element => element == "Noida"));
            }
        }

This console application declares an array of strings called StateDetails and then uses the Array. Exists method to check if certain conditions are true for the elements of the Array.The first Console.WriteLine statement checks if at least one element in the StateDetails Array begins with the letter N. It uses a lambda expression element => element. The Array. StartsWith(N) to define a function that takes an element of the Array as an argument and returns a boolean indicating whether the element starts with the letter N. Exists method applies this function to each element of the Array and returns true if at least one of the elements satisfies the condition.

The second Console.WriteLine statement checks if at least one element in the StateDetails Array begins with the letter B. It uses a similar lambda expression to define the condition.

The third Console.WriteLine statement checks if the string Noida is an element of the StateDetails Array. It uses the equality operator == to compare each element of the Array to the string Noida and returns true if it finds a match. When this program is executed, it will output three lines of text indicating whether the specified conditions are true or false for the elements of the StateDetails Array.
Output 

  

Conclusion   

In this article, you will learn about the code that taught usHow to check if an array contains a specific element in C#. Also, check out Working with Arrays in C# (code included), and check out Working with Arrays in C# (code included) 

FAQs 

Q- How do you check if an array contains a specific element in C#?
A- You can check if an array contains a specific element in C# by using the Contains() method provided by the System.Linq namespace.  

Q- Is there an alternative to using the Contains() method to check if an array contains a specific element in C#?
A- Yes, another way to check if an array contains a specific element in C# is to use a loop to iterate over each element in the Array and compare it to the value you are searching for. 

Q- What happens if you try to use the Contains() method on an array null in C#?
A- If you try to use the Contains() method on an array null in C#, you will get a NullReferenceException at runtime. This is because the Contains() method is an instance method that operates on an instance of the Array class, and calling an instance method on null reference results in a NullReferenceException. To avoid this, you should always check if the array reference is null before using the Contains() method. 


Similar Articles