This post will discuss how to check the existence of a given element in an array in C#. The solution should return true if the array contains the specified value; otherwise, false.

1. Using Enumerable.Contains() method (System.Linq)

The Enumerable.Contains() method provides a simple, clean way to determine whether a sequence contains a specified element or not. The following example demonstrates the usage of the Contains() method:

Download  Run Code

2. Using Array.Exists() method

The Array.Exists() method is the recommended solution is to check the existence of an element in an array. The following code example shows how to implement this.

Download  Run Code

3. Using Array.IndexOf() method

Another good solution is to use the Array.IndexOf() method that returns the index of the first occurrence of the specified element in this array and -1 if there is no such element.

Download  Run Code

4. Using Array.FindIndex() method

Array.FindIndex() returns the index of the first element that satisfies the provided predicate. If no element satisfies the condition, FindIndex returns -1.

Download  Run Code

5. Using HashSet

HashSet class provides the Contains method to determine whether the set object contains the specified element. The following example converts the given array to a set and calls its Contains method:

Download  Run Code

6. Using Enumerable.Where() method (System.Linq)

The System.Linq.Enumerable.Where() method filters a sequence of values based on a predicate. The following code example demonstrates how we can use Where() to find the first occurrence of the specified element in this array.

Download  Run Code

 
We can avoid the try-catch block by setting the default value with the DefaultIfEmpty() method:

Download  Run Code

7. Using Array.FindAll() method

Array.FindAll() method returns an array containing all the elements that match the specified predicate. We can use it as following to check for the existence of an element in the array.

Download  Run Code

A naive solution is to perform a linear search on the given array to determine whether the target element is present in the array.

Download  Run Code

That’s all about finding an element in an array in C#.