EN
C# / .NET - compare arrays
3
points
In this article, we would like to show you how to compare two arrays in C#.
Note:
As arrays comparison, we understand size and array items comparison. That comparision may be realised using embedded
SequenceEqual()method.
Quick solution:
// using System.Linq;
int[] array1 = new int[] { 1, 2, 3 };
int[] array2 = new int[] { 1, 2, 3 };
Console.WriteLine(array1.SequenceEqual(array2)); // True
Items comparion example
In this section, we can see items comparions example.
// using System.Linq;
int[] array1 = new int[] { 1, 2, 3 };
int[] array2 = new int[] { 1, 2, 3 };
int[] array3 = new int[] { 3, 2, 1 };
Console.WriteLine(array1.SequenceEqual(array2));
Console.WriteLine(array1.SequenceEqual(array3));
Output:
True
False
References comparion example
The example presented in this section is useful when we want to check if 2 variables indicate same array object in the memory.
int[] array1 = new int[] { 1, 2, 3 };
int[] array2 = new int[] { 1, 2, 3 };
Console.WriteLine(array1 == array1);
Console.WriteLine(array1 == array2);
Console.WriteLine(array2 == array2);
Output:
True
False
True