Check if array A contains all elements of array B and vice versa irrespective of order I am trying to check if an Array A contains all the elements of Array B and similarly Array B contains elements of Array A, the order does not matter.

Some examples:




A               B                Result 
{1}             {0}              false
{0, 0, 0}       {0, 0, 0}        true
{17, 4, 11}     {4, 17, 11}      true



I have written the following code:



public static bool CheckEquality(int[] a, int[] b) 
{
    return Array.TrueForAll(a, m =&gt; b.Count(z =&gt; m == z) == a.Count(z =&gt; m == z)) &amp;&amp; a.Length == b.Length;
}


Both arrays contain just integers. Both arrays should strictly contain the same number of the same elements, and their lengths should be equal.

Is there a better and efficient way to do this?
You can check this by keeping track of each value in a dictionary: adding one for items in the first array, subtracting one for items in the second array and finally checking that all tracked values are zero.

Also, implemented this way, there is no need to make the method array- or int-specific.

public static bool CheckEquality&lt;T&gt;(IEnumerable&lt;T&gt; first, IEnumerable&lt;T&gt; second)
{
    var dictionary = new Dictionary&lt;T, int&gt;();

    Action&lt;IEnumerable&lt;T&gt;, int&gt; setCounts = (items, change) =&gt;
    {
        foreach (var item in items)
        {
            int count;
            // if not found, count will be the default value of 0
            dictionary.TryGetValue(item, out count);
            dictionary[item] = count + change;
        }
    };

    setCounts(first, +1);
    setCounts(second, -1);

    return dictionary.Values.All(value =&gt; value == 0);
}


The code is more complicated than sorting arrays, but it's also \$O(n)\$.