Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

Need to compare two arrays of any primitive type for equality

Posted on 2014-10-16
2
Medium Priority
?
135 Views
Last Modified: 2014-11-05
I need a method that will compare two arrays of any primitive type for the same contents.  Any order.
0
Comment
Question by:Bruce
2 Comments
 
LVL 36

Expert Comment

by:ste5an
ID: 40386149
Imho there is no way to tell, whether you have a sequential memory layout, thus you should stick to SequenceEqual.
0
 
LVL 35

Accepted Solution

by:
sarabande earned 2000 total points
ID: 40386251
you may try

bool arraysAreEqual = (array1.Length == array2.Length) 
                     && new HashSet<T>(array1).SetEquals(array2);

Open in new window


in case the arrays haven't duplicate values.

if duplicates could happen use

SortedDictionary<T, int> dict1 = new SortedDictionary<T, int>();
SortedDictionary<T, int> dict2 = new SortedDictionary<T, int>();
foreach (t in array1) 
     dict1[t]++;  // count occurences
foreach (t in array2) 
     dict2[t]++; // count occurences
bool areArraysEqual = dict1.SequenceEqual(dict2);

Open in new window

or use a function like

static bool AreArraysEqual<T>(T[] array1, T[] array2)
{
    if (array1.Length != array2.Length)
        return false;
    Array.Sort(array1);
    Array.Sort(array2);

    EqualityComparer<T> comparer = EqualityComparer<T>.Default;
    for (int i = 0; i < array1.Length; i++)
    {
        if (!comparer.Equals(array1[i], array2[i])) return false;
    }
    return true;}

Open in new window


Sara
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Many of us here at EE write code. Many of us write exceptional code; just as many of us write exception-prone code. As we all should know, exceptions are a mechanism for handling errors which are typically out of our control. From database errors, t…
More often than not, we developers are confronted with a need: a need to make some kind of magic happen via code. Whether it is for a client, for the boss, or for our own personal projects, the need must be satisfied. Most of the time, the Framework…
In a question here at Experts Exchange (https://www.experts-exchange.com/questions/29062564/Adobe-acrobat-reader-DC.html), a member asked how to create a signature in Adobe Acrobat Reader DC (the free Reader product, not the paid, full Acrobat produ…
Loops Section Overview
Suggested Courses

971 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question