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?
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.
compareArray() will compare elements of both of the array elements and returns 0 if all elements are equal otherwise function will return 1.
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));
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With