使用正确实现的比较器的SortedList <>/SortedDictionary <>可以用来保证插入顺序吗?

J S*_*ith 3 c# dictionary hashtable sortedlist sorteddictionary

如果目标是创建一个保留插入顺序的通用只读字典,那么SortedList <,>或SortedDictionary <,>是否可以与IComparer <>一起使用,它试图通过执行类似下面的操作来维护插入顺序?

class OrderedComparer<T> : IComparer<M>
{
    public int Compare(M x, M y)
    {
        return x.Equals(y) ? 0 : -1;//or 1
    }
}
SortedList<M> orderedList = new SortedList<M>(new OrderedComparer<T>());
Run Code Online (Sandbox Code Playgroud)

(有趣的是,在SortedDictionary的情况下,上述方法需要返回0或1以防止元素按反向插入顺序排序).

usr*_*usr 5

比较者必须遵守法律

Compare(a, b) == -Compare(b, a) //assuming only possible values are -1, 0, 1
Run Code Online (Sandbox Code Playgroud)

这是对称属性.您的示例代码不遵守它.因此BCL系列根本不给您任何保证.您违反了记录的合同.

你不能这样做.

相反,您可以将新字段添加到M存储插入订单的位置int.然后,您可以在比较器中使用该字段.

  • 重要提示:正确的“法则”是 `Compare(a,b) &gt; 0 == Compare(b,a) &lt; 0 &amp;&amp; (Compare(a,b) == 0) == (Compare(b,a) == 0) &amp;&amp; Compare(a,b) &lt; 0 == Compare(b,a) &gt; 0` 当您只有 -1, 0, 1 的可能输出时,答案中所述的只是一种简化形式。 (2认同)