Sort List<T> by reference
<p>I would like to sort a <code>List&lt;T&gt;</code> by reference. Why? I want to compare several lists and find which elements are unique to a given list. Sorting them first in some canonical fashion and then stepping through all lists simultaneously seems a good way to do this. This essentially means that I need to make aa <code>IComparer&lt;T&gt;</code> that returns a non-zero integer for different references (and is consistent). The order does have to mean anything, but just provide a fixed order for all <code>T</code> for at least the time it takes me to get the job done.</p>

<p><code>GetHashCode</code> can return the same value for two different objects on a 64-bit system, so that is out as a way to do a comparison.</p>

<p><code>IntPtr</code> from <code>AddrOfPinnedObject()</code> might work since it has the correct size, but I have to pin the object for the duration of the process.</p>

<p>Making a <code>Dictionary&lt;T, long&gt;</code> where the <code>long</code> is issued first-come first-served is what I'm going with now, but I want to know if there are better options. The hash lookup seems unnecessary.</p>

<p>What is the best way to define <code>ReferenceComparer&lt;T&gt; : IComparer&lt;T&gt;</code> to give me that fixed ordering?</p>

<p>Here is the dictionary implementation:</p>

<pre><code>public class ReferenceComparer&lt;T&gt; : IComparer&lt;T&gt;
{
    private long nextAvailable = 0;
    private readonly Dictionary&lt;T, long&gt; objectToLong = new Dictionary&lt;T, long&gt;(new AsObjectEqualityComparer&lt;T&gt;());

    public int Compare(T x, T y)
    {
        long xLong;
        if (!objectToLong.TryGetValue(x, out xLong))
        {
            xLong = nextAvailable;
            objectToLong[x] = xLong;
            nextAvailable = nextAvailable + 1;
        }

        long yLong;
        if (!objectToLong.TryGetValue(y, out yLong))
        {
            yLong = nextAvailable;
            objectToLong[y] = yLong;
            nextAvailable = nextAvailable + 1;
        }

        return xLong.CompareTo(yLong);
    }
}
</code></pre>