Testing equality of arrays in C#

arrays, c#

Solution

Assuming that the values in the array are unique, you can implement a performant solution using LINQ:

// create a LINQ query that matches each item in ar1 with 
// its counterpart in ar2. we select "1" because we're only 
// interested in the count of pairs, not the values.
var q = from a in ar1 
        join b in ar2 on a equals b 
        select 1;

// if lengths of the arrays are equal and the count of matching pairs 
// is equal to the array length, then they must be equivalent.
bool equals = ar1.Length == ar2.Length && q.Count() == ar1.Length;

// when q.Count() is called, the join in the query gets translated
// to a hash-based lookup code which can run faster than nested
// for loops. 

Problem

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?

Original source

Related problems