| by Arround The Web | No comments

How to Check If a C# Array Contains a Specific Value

It comes as no surprise that arrays are some of C#’s most fundamental data structures.

We can define an array as a data structure that allows us to store a collection of the same data type in contiguous memory locations. An array is defined with a fixed size which allows for efficient access of the elements using their index position.

One of the most common operations when working with arrays is determining if an array contains a specific value.

In this tutorial, we will explore all the various methods and techniques that you can employ in the C# language.

Method 1: Using the Array.Contains() Method

The most common and simplest method of checking whether an array contains a given value is the “contains” method. This method is part of the “Array” collection which provides an easy way to perform an ordinary operation.

Consider the following example that demonstrates how to use the Contains() method:

using System;
class Program
{
    static void Main()
    {
        int[] numbers = { 1, 2, 3, 4, 5 };
        bool containsValue = Array.Exists(numbers, element => element == 4);
        if (containsValue)
        {
            Console.WriteLine($"Array contains {4}");
        }
        else
        {
            Console.WriteLine($"Array does not contain the specified value.");
        }
    }
}

The given code defines a new array of integers containing five elements.

We then use the Array.Exists() method to check if the target value exists in the array. We also include a lambda expression as a condition to check if any element in the array is equal to the target value.

We then store the result of the Array.Exists() method to store it in the “containsValue” variable which returns “True” if the array contains the target and returns “False” otherwise.

Finally, we use a basic “if…else” statement to print the corresponding message to the console.

Method 2: Using the Array.IndexOf() Method

The second method that we can use to check if an element exists in a given array is the Array.IndexOf() method.

This method allows us to search for the specified object and return the index of the first occurrence of that element in a one-dimensional array.

The following shows the syntax of the IndexOf() method:

public static int IndexOf (Array array, object? value);

The function accepts two main parameters:

  1. Array – This specifies a one-dimensional array to search.
  2. Value – This specifies the object that we wish to locate in the array.

The function then returns an int32 data type that represents the first occurrence of the value in the collection.

The following shows how to use the IndexOf() method to check if an element exists in an array:

using System;
class Program
{
    static void Main()
    {
        int[] numbers = { 1, 2, 3, 4, 5 };
        int index = Array.IndexOf(numbers, 4);
        if (index != -1)
        {
            Console.WriteLine($"Array contains {4} at index {index}");
        }
        else
        {
            Console.WriteLine($"Array does not contain the specified element");
        }
    }
}

The given code uses the IndexOf() method to locate the first occurrence of element 4 in the array.

Method 3: Using C# LINQ

C# also provides us with the LINQ feature which allows us to check if an array contains a specific value in a more flexible and readable method. This method works with various collection types.

An example is as follows:

using System;
class Program
{
    static void Main()
    {
        int[] numbers = { 1, 2, 3, 4, 5 };
        bool containsValue = numbers.Any(x => x == 4);

        if (containsValue)
        {
            Console.WriteLine($"Array contains the element");
        }
        else
        {
            Console.WriteLine($"Array does not contain specified value");
        }
    }
}

This uses the Any() method to check if the array contains the specified value and saves the result to the “containsValue” variable as a bool.

Method 4: Using the Basic Iterator

As you can guess, we can use the “for” loop in C# to check if an element exists in a given array. It is good to keep in mind that this method is very inefficient when working with vast arrays, as the time required increases exponentially with the number of elements in the collection.

Consider the following example:

using System;
class Program
{
    static void Main()
    {
        int[] numbers = { 1, 2, 3, 4, 5 };
        bool containsValue = false;
        foreach (int number in numbers)
        {
            if (number == 4)
            {
                containsValue = true;
                break;
            }
        }
        if (containsValue)
        {
            Console.WriteLine($"Array contains value");
        }
        else
        {
            Console.WriteLine($"Array does not contain value");
        }
    }
}

This method uses a “for” loop to iterate over each array element. We then manually check if each array component equals the target value. If it returns “true”, we save the result into the value.

Conclusion

In this tutorial, we learned the four main methods that we can use to check whether an array contains a given element in the C# language.

Share Button

Source: linuxhint.com

Leave a Reply