This post will check if two arrays are equal or not in C#.

Two arrays are considered equal in C# if both sequences have equal length and contain identical data in the same order. We can check array equality using any of the following methods:

1. Using Enumerable.SequenceEqual() method

To check for array equality, we can use the Enumerable.SequenceEquals() method in the System.Linq namespace. This works by checking whether two source sequences are of equal length and their corresponding elements are equal according to the default equality comparer for their type.

The following example demonstrates the usage of the SequenceEqual() method to determine whether two sequences are equal.

Download  Run Code

 
The above code can be rewritten as follow:

Download  Run Code

2. Custom Routine

We can also write our own custom routine to compare two generic arrays. The routine should determine whether the compared sequences contain references to the same objects and compare the objects’ actual data within the sequences. To compare the objects’ actual data in the sequences, we can use EqualityComparer<T>.

This is demonstrated below:

Download  Run Code

That’s all about comparing two arrays for equality in C#.