1

Compare two arrays. Return true if first array has same items as second array, even if they are in different positions. Here are two possible arrays:

int[] arrayA = { 1, 2, 3 };
int[] arrayB = { 3, 2, 1 };

I can only find if arrayB has a single number in arrayA.

Dinamo
  • 15
  • 4
  • 1
    Possible duplicate of [Easiest way to compare arrays in C#](https://stackoverflow.com/questions/3232744/easiest-way-to-compare-arrays-in-c-sharp) – Hien Nguyen Apr 20 '19 at 12:08
  • Possible duplicate of [Is there a built-in method to compare collections?](https://stackoverflow.com/questions/43500/is-there-a-built-in-method-to-compare-collections) – canton7 Apr 21 '19 at 18:32

2 Answers2

0

One method to solve this would be create a HashSet<int> from each array, then use .SetEquals(HashSet<int> hashSet) to check if they have the same values.

public static bool CompareArrays(int[] array1, int[] array2)
{
    // Create sets using Linq
    HashSet<int> set1 = array1.ToHashSet();
    HashSet<int> set2 = array2.ToHashSet();
    // Compare the sets with .SetEquals()
    return set1.SetEquals(set2);
}
jmorjsm
  • 33
  • 1
  • 5
0

You could use the SequenceEqual method (LINQ).

bool areEqual = arrayA.OrderBy(n => n).SequenceEqual(arrayB.OrderBy(n => n));
Theodor Zoulias
  • 34,835
  • 7
  • 69
  • 104
  • This is more expensive than `arrayA.ToHashSet().SetEquals(arrayB)`. – canton7 Apr 21 '19 at 10:49
  • @canton7 it may be more expensive, but it is still preferable because it produces correct results. Instead `set1.SetEquals(set2)` will erroneous report that the arrays { 1, 2, 1 } and { 1, 2, 2 } are equal, because it ignores duplicate elements. – Theodor Zoulias Apr 21 '19 at 18:25
  • Very true. There are ways around this which use a Dictionary, and also don't require that your items are comparable. – canton7 Apr 21 '19 at 18:44
  • @canton7 agreed. – Theodor Zoulias Apr 21 '19 at 19:02
  • @canton7 you may want to provide a performant and correct implementation using Dictionaries. I have already offered an answer, and I think it's not right to offer a second one. – Theodor Zoulias Apr 21 '19 at 19:11
  • See duplicates, like this one: https://stackoverflow.com/questions/50098/comparing-two-collections-for-equality-irrespective-of-the-order-of-items-in-the – canton7 Apr 21 '19 at 20:25
  • @canton7 yeap, you are correct. I forgot it's a duplicate question. :-) – Theodor Zoulias Apr 21 '19 at 20:31