C# Check if Array Contains Specific Element

To check if an array contains a specific element in C#, call Array.Exists() method and pass the array and the predicate that the element is specified element as arguments.

If the element is present in the array, Array.Exists() returns true, else it returns false.

Examples

In the following example, we take an array of strings arr, and check if the element "cherry" is present in this array using Array.Exists().

Program.cs

</>
Copy
using System;

namespace CSharpExamples {
    class Program {
        static void Main(string[] args) {
            string[] arr = { "apple", "banana", "cherry", "mango" };
            string searchElement = "cherry";
            bool exists = Array.Exists( arr, element => element == searchElement  );
            if (exists) {
                Console.WriteLine( "Array contains specified element." );
            } else {
                Console.WriteLine( "Array does not contain specified element." );
            }
        }
    }
}

Output

Array contains specified element.

Now, let us take an element which is not present in the array, and programmatically check if this element is present in the array.

Program.cs

</>
Copy
using System;

namespace CSharpExamples {
    class Program {
        static void Main(string[] args) {
            string[] arr = { "apple", "banana", "cherry", "mango" };
            string searchElement = "guava";
            bool exists = Array.Exists( arr, element => element == searchElement  );
            if (exists) {
                Console.WriteLine( "Array contains specified element." );
            } else {
                Console.WriteLine( "Array does not contain specified element." );
            }
        }
    }
}

Output

Array does not contain specified element.

Conclusion

In this C# Tutorial, we learned how to check if an array contains a specified element using Array.Exists(), with examples.