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?
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?
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.
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);
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;
var shared = arr1.Intersect(arr2);
bool equals = arr1.Length == arr2.Length && shared.Count() == arr1.Length;
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));
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.
For the most efficient approach (Reflectored from Microsoft code), see here:
http://stackoverflow.com/questions/50098/comparing-two-collections-for-equality/3790621#3790621