title: Comparing two collections for equality irrespective of the order of items in them
body: <p>I would like to compare two collections (in C#), but I'm not sure of the best way to implement this efficiently.</p>
  
  <p>I've read the other thread about <a href="https://stackoverflow.com/questions/43500/is-there-a-built-in-method-to-compare-collections-in-c">Enumerable.SequenceEqual</a>, but it's not exactly what I'm looking for.</p>
  
  <p>In my case, two collections would be equal if they both contain the same items (no matter the order).</p>
  
  <p>Example:</p>
  
  <pre><code>collection1 = {1, 2, 3, 4};
  collection2 = {2, 4, 1, 3};
  
  collection1 == collection2; // true
  </code></pre>
  
  <p>What I usually do is to loop through each item of one collection and see if it exists in the other collection, then loop through each item of the other collection and see if it exists in the first collection. (I start by comparing the lengths).</p>
  
  <pre><code>if (collection1.Count != collection2.Count)
      return false; // the collections are not equal
  
  foreach (Item item in collection1)
  {
      if (!collection2.Contains(item))
          return false; // the collections are not equal
  }
  
  foreach (Item item in collection2)
  {
      if (!collection1.Contains(item))
          return false; // the collections are not equal
  }
  
  return true; // the collections are equal
  </code></pre>
  
  <p>However, this is not entirely correct, and it's probably not the most efficient way to do compare two collections for equality.</p>
  
  <p>An example I can think of that would be wrong is:</p>
  
  <pre><code>collection1 = {1, 2, 3, 3, 4}
  collection2 = {1, 2, 2, 3, 4}
  </code></pre>
  
  <p>Which would be equal with my implementation. Should I just count the number of times each item is found and make sure the counts are equal in both collections?</p>
  
  <hr>
  
  <p>The examples are in some sort of C# (let's call it pseudo-C#), but give your answer in whatever language you wish, it does not matter.</p>
  
  <p><strong>Note:</strong> I used integers in the examples for simplicity, but I want to be able to use reference-type objects too (they do not behave correctly as keys because only the reference of the object is compared, not the content).</p>