Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing equality of arrays in C#

Tags:

arrays

c#

I have two arrays. For example:

int[] Array1 = new[] {1, 2, 3, 4, 5, 6, 7, 8, 9}; int[] Array2 = new[] {9, 1, 4, 5, 2, 3, 6, 7, 8}; 

What is the best way to determine if they have the same elements?

like image 827
SudheerKovalam Avatar asked Mar 16 '09 06:03

SudheerKovalam


People also ask

How do you check if two arrays are equality?

The Arrays. equals() method checks the equality of the two arrays in terms of size, data, and order of elements. This method will accept the two arrays which need to be compared, and it returns the boolean result true if both the arrays are equal and false if the arrays are not equal.

Can we compare 2 arrays in C?

compareArray() will compare elements of both of the array elements and returns 0 if all elements are equal otherwise function will return 1.


2 Answers

You could also use SequenceEqual, provided the IEnumerable objects are sorted first.

int[] a1 = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };     int[] a2 = new[] { 9, 1, 4, 5, 2, 3, 6, 7, 8 };      bool equals = a1.OrderBy(a => a).SequenceEqual(a2.OrderBy(a => a)); 
like image 66
Mike Nislick Avatar answered Oct 05 '22 03:10

Mike Nislick


By using LINQ you can implement it expressively and performant:

var q = from a in ar1         join b in ar2 on a equals b         select a;  bool equals = ar1.Length == ar2.Length && q.Count() == ar1.Length; 
like image 42
Sedat Kapanoglu Avatar answered Oct 05 '22 03:10

Sedat Kapanoglu