排序列表(SortedList)/排序字典(SortedDictionary)是否可以使用正确实现的比较器来保证插入顺序? [英] Can a SortedList<>/SortedDictionary<> with a properly implemented comparer be used to guarantee insertion order?

查看:114
本文介绍了排序列表(SortedList)/排序字典(SortedDictionary)是否可以使用正确实现的比较器来保证插入顺序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果目标是创建保留插入顺序的通用只读词典,可以将SortedList<,>或SortedDictionary<,>与尝试维护插入的IComparer<>结合使用。

If the goal is to create a generic read-only dictionary that preserves insertion order, can SortedList<,> or SortedDictionary<,> be realiably used with an IComparer<> that attempts to maintain insertion order by doing something similar to the following?

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>());

(有趣的是,对于SortedDictionary,上述方法需要按顺序返回0或1防止元素按照相反的插入顺序排序。)

(It's interesting that in the case of SortedDictionary, the above method need to return 0 or 1 in order to prevent the elements from being sorted in the reverse insertion order).

推荐答案

比较器必须遵守法律

Compare(a, b) == -Compare(b, a) //assuming only possible values are -1, 0, 1

这是对称属性。您的示例代码不遵守。因此,BCL集合根本无法为您提供任何保证。您违反了书面合同。

This is the symmetry property. Your sample code does not obey it. Therefore the BCL collections do not give you any guarantee at all. You have violated the documented contract.

您不能这样做。

相反,您可以添加一个 M 的新字段,您将插入订单存储为 int 。然后,您可以在比较器中使用该字段。

Instead, you could add a new field to M where you store the insertion order as an int. You can then use that field in the comparer.

这篇关于排序列表(SortedList)/排序字典(SortedDictionary)是否可以使用正确实现的比较器来保证插入顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆