This post will discuss how to compare arrays in C#. The solution checks for structural equality, where two arrays are considered equal if they have equal values.

The == operator checks for reference equality in C#. To check for structural equality, you can use any of the following methods.

1. Using Enumerable.SequenceEqual Method

The Enumerable.SequenceEqual method in LINQ can check whether two arrays are equal. This method is available with .NET framework 3.5 or higher. It works by comparing corresponding elements of both sequences using the custom or default equality comparer.

Download  Run Code

 
If the array is not null, you can directly call the SequenceEqual() method upon an array to compare its contents with the specified array.

Download  Run Code

 
To determine if two arrays have the same elements, compare their sorted copies with the SequenceEqual() method like:

Download  Run Code

2. Using string.Join Method

Alternatively, you can just compare the string representation of both arrays with the == operator. The following solution uses String.Join method to concatenate elements of the specified array with the specified separator.

Download  Run Code

3. Using custom routine

Finally, you can write a custom routine for checking the equality of two arrays. The idea is to iterate over the array elements and invoke the Equals() method on each element. This can be implemented as follows in C#.

Download  Run Code

That’s all about comparing arrays in C#.