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:
xxxxxxxxxx
1
// using System.Linq;
2
3
int[] array1 = new int[] { 1, 2, 3 };
4
int[] array2 = new int[] { 1, 2, 3 };
5
6
Console.WriteLine(array1.SequenceEqual(array2)); // True
In this section, we can see items comparions example.
xxxxxxxxxx
1
// using System.Linq;
2
3
int[] array1 = new int[] { 1, 2, 3 };
4
int[] array2 = new int[] { 1, 2, 3 };
5
int[] array3 = new int[] { 3, 2, 1 };
6
7
Console.WriteLine(array1.SequenceEqual(array2));
8
Console.WriteLine(array1.SequenceEqual(array3));
Output:
xxxxxxxxxx
1
True
2
False
The example presented in this section is useful when we want to check if 2 variables indicate same array object in the memory.
xxxxxxxxxx
1
int[] array1 = new int[] { 1, 2, 3 };
2
int[] array2 = new int[] { 1, 2, 3 };
3
4
Console.WriteLine(array1 == array1);
5
Console.WriteLine(array1 == array2);
6
Console.WriteLine(array2 == array2);
Output:
xxxxxxxxxx
1
True
2
False
3
True