SudheerKovalam SudheerKovalam - 2 months ago 11
C# Question

Testing equality of arrays in 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?

Answer

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;