Languages
[Edit]
EN

C# / .NET - compare arrays

3 points
Created by:
Zeeshan-Peel
850

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

References

  1. Enumerable.SequenceEqual Method (System.Linq) | Microsoft Docs 
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join