tags:

views:

1597

answers:

7

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?

+1  A: 

I have found the solution detailed here to be a very clean way, though a bit verbose for some people.

The best thing is that it works for other IEnumerables as well.

Cerebrus
That link describes SequenceEqual (in .NET 3.5), and will return false on this data since they are in a different order.
Marc Gravell
For reference, it would be (using extension methods) bool areEqual = array1.SequenceEqual(array2);
Marc Gravell
+5  A: 

Will the values always be unique? If so, how about (after checking equal length):

var set = new HashSet<int>(array1);
bool allThere = array2.All(set.Contains);
Marc Gravell
+4  A: 

How about LINQ:

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;
ssg
Thanks for this code snippet. Works like a charm for my scenario!!
SudheerKovalam
I find this to be much slower than just doing a loop and comparing each item. The loop may not be as nice looking, but much, much faster.
David Basarab
I'm not sure about that. As far as I know LINQ-to-Objects generate intermediate hash tables to loop over joins which are much faster than a straight loop.
ssg
Here is my reference: http://stackoverflow.com/questions/1561622/is-linq-join-operator-using-nested-loop-merge-or-hashset-joins
ssg
+4  A: 
var shared = arr1.Intersect(arr2);
bool equals = arr1.Length == arr2.Length && shared.Count() == arr1.Length;
eglasius
+3  A: 

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));
Mike Nislick
+1  A: 

Use extension methods (which are new in 3.0). If the length of the Intersection of the two arrays equals that of their Union then the arrays are equal.

bool equals = arrayA.Intersect(arrayB).Count() == arrayA.Union(arrayB).Count()

Succinct.

Allen
+1  A: 

For the most efficient approach (Reflectored from Microsoft code), see here:

http://stackoverflow.com/questions/50098/comparing-two-collections-for-equality/3790621#3790621

ohadsc