C#:枚举 SortedDictionary 时它是否已排序?
SorteDictionary 是根据 MSDN 对键进行排序的。 这是否意味着当您在 foreach 中枚举它时可以确定它会被排序? 或者这只是意味着 SortedDictionary 在内部以这种方式工作以便在各种情况下具有更好的性能?
A SorteDictionary is according to MSDN sorted on the key. Does that mean that you can be sure that it will be sorted when you enumerate it in a foreach? Or does it just mean that the SortedDictionary works that way internally to have better performance in various cases?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
来自 MSDN:
From MSDN:
当您枚举集合时,它会按键排序(即使您枚举
Values
集合)。 在内部,该集合被实现为二叉搜索树(根据文档)。 值的插入和查找都是 O(log n)(意味着它们非常高效)。When you enumerate the collection it is sorted by keys (even if you enumerate say the
Values
collection). Internally the collection is implemented as a binary search tree (according to the documentation). Both insertion and lookup of values are O(log n) (meaning they are pretty efficient).如果您枚举
SortedDictionary
中的项目,这些项目将按项目键的排序顺序返回。 如果您通过SortedDictionary
中的键进行枚举,键也将按排序顺序返回。 也许有些令人惊讶的是,如果您通过其值枚举SortedDictionary
,则这些值会按键的排序顺序返回,而不是您可能会看到的值的排序顺序预计。演示:
请注意,在此演示中,添加到
SortedDictionary
的项目未按排序顺序添加。另外,如果您打算按字典的值枚举字典,并且可能存在重复值,请考虑使用反向查找功能返回一个 IEnumerable 。 (当然,对于大型字典,通过值查找键可能会导致性能不佳。)
预期输出:
If you enumerate the items in a
SortedDictionary
, the items will be returned in the sort order of the item keys. And if you enumerate by the keys in theSortedDictionary
, the keys will also be returned in sorted order. And perhaps somewhat surprisingly, if you enumerate theSortedDictionary
by its values, the values are returned in the sort order of the keys, not the sort order of the values as you might expect.Demonstration:
Note that in this demo the items added to the
SortedDictionary
are not added in sorted order.Also, if you plan to enumerate your dictionary by its values and there is a possibility of duplicate values, consider having your reverse lookup function return an IEnumerable<T>. (Of course, for large dictionaries, looking up a key by its value may result in poor performance.)
Expected Output:
是的,这正是它的意思。
编辑:“这是否意味着当您在 foreach 中枚举它时可以确定它会被排序?”的部分
Yes, that's exactly what it means.
Edit: the part that says "Does that mean that you can be sure that it will be sorted when you enumerate it in a foreach?"