title: Comparison method for sorting that shuffles equal elements randomly
body: <p>Here's a puzzle for you.</p>
  
  <p>I want to change the following comparison method, so that when two items are considered equal, they will be shuffled randomly.</p>
  
  <pre><code>myList.Sort( (x, y) =&gt; x.Score.CompareTo(y.Score) );
  </code></pre>
  
  <p>I could imagine that this scenario would be useful when ordering search results if you didn't want to give preference to one result over another when their scores are the same.</p>
  
  <p>Anyone want to give it a go?</p>
  
  <p>Here was my first attempt at a solution, but it doesn't work. I'll let you figure out why.</p>
  
  <pre><code>class RandomizeWhenEqualComparer&lt;T&gt; : IComparer&lt;T&gt;
  {
      private readonly Func&lt;T, T, int&gt; _comparer;
  
      public int Compare(T x, T y)
      {
              if (x.Equals(y)) return 0;
  
          int result = _comparer(x, y);
  
          if (result != 0) return result;
  
          double random = StaticRandom.NextDouble();
          return (random &lt; .5) ? -1 : 1;
      }
  
      public RandomizeWhenEqualComparer(Func&lt;T, T, int&gt; comparer)
      {
          _comparer = comparer;
      }
  }
  </code></pre>