Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
Solved

# Need to compare two arrays of any primitive type for equality

Posted on 2014-10-16
Medium Priority
130 Views
I need a method that will compare two arrays of any primitive type for the same contents.  Any order.
0
Question by:Bruce
[X]
###### Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

• Help others & share knowledge
• Earn cash & points

LVL 35

Expert Comment

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

sarabande earned 2000 total points
ID: 40386251
you may try

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

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);
``````
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;}
``````

Sara
0

## Featured Post

Question has a verified solution.

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

Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
This article aims to explain the working of CircularLogArchiver. This tool was designed to solve the buildup of log file in cases where systems do not support circular logging or where circular logging is not enabled
In this video, Percona Director of Solution Engineering Jon Tobin discusses the function and features of Percona Server for MongoDB. How Percona can help Percona can help you determine if Percona Server for MongoDB is the right solution for …
In response to a need for security and privacy, and to continue fostering an environment members can turn to for support, solutions, and education, Experts Exchange has created anonymous question capabilities. This new feature is available to our Pr…
###### Suggested Courses
Course of the Month7 days, 5 hours left to enroll