title: Testing for equality between dictionaries in C#
body: <p>Assuming dictionary keys and values have their equals and hash methods implemented correctly, what is the most succinct and efficient way to test for equality of two dictionaries?</p>
  <p>In this context, two dictionaries are said to be equal if they contain the same set of keys (order not important), and for every such key, they agree on the value.</p>
  <p>Here are some ways I came up with (there are probably many more):</p>
  <pre><code>public bool Compare1&lt;TKey, TValue&gt;(
      Dictionary&lt;TKey, TValue&gt; dic1, 
      Dictionary&lt;TKey,TValue&gt; dic2)
  {
      return dic1.OrderBy(x =&gt; x.Key).
          SequenceEqual(dic2.OrderBy(x =&gt; x.Key));
  }
  
  public bool Compare2&lt;TKey, TValue&gt;(
      Dictionary&lt;TKey, TValue&gt; dic1, 
      Dictionary&lt;TKey, TValue&gt; dic2)
  {
      return (dic1.Count == dic2.Count &amp;&amp; 
          dic1.Intersect(dic2).Count().
          Equals(dic1.Count));
  }
  
  public bool Compare3&lt;TKey, TValue&gt;(
      Dictionary&lt;TKey, TValue&gt; dic1, 
      Dictionary&lt;TKey, TValue&gt; dic2)
  {
      return (dic1.Intersect(dic2).Count().
          Equals(dic1.Union(dic2).Count()));
  }
  </code></pre>