问题描述
我有一本 C# 字典,比如
I have a dictionary in C# like
Dictionary<Person, int>
并且我想根据键(Person 类中的一个字段)对字典进行就地排序.我该怎么做?互联网上所有可用的帮助都是列表,没有特定的字典就地排序示例.任何帮助将不胜感激!
and I want to sort that dictionary in place with respect to keys (a field in class Person). How can I do it? Every available help on the internet is that of lists with no particular example of in place sorting of Dictionary. Any help would be highly appreciated!
推荐答案
您无法对 Dictionary
进行排序 - 它本质上是无序的.(或者更确切地说,检索条目的顺序是特定于实现的.您不应该依赖它在版本之间以相同的方式工作,因为排序不是其设计功能的一部分.)
You can't sort a Dictionary<TKey, TValue>
- it's inherently unordered. (Or rather, the order in which entries are retrieved is implementation-specific. You shouldn't rely on it working the same way between versions, as ordering isn't part of its designed functionality.)
您可以使用SortedList
或 SortedDictionary
,两者都按键排序(以可配置的方式,如果您将 IEqualityComparer
传递给构造函数)- 这些对你有用吗?
You can use SortedList<TKey, TValue>
or SortedDictionary<TKey, TValue>
, both of which sort by the key (in a configurable way, if you pass an IEqualityComparer<T>
into the constructor) - might those be of use to you?
很少注意名称SortedList
中的list"这个词——它仍然是一个字典,因为它将键映射到值.它在内部使用列表实现,有效 - 因此它不是通过哈希码查找,而是进行二进制搜索.SortedDictionary
类似地基于二分搜索,但通过树而不是列表.
Pay little attention to the word "list" in the name SortedList
- it's still a dictionary in that it maps keys to values. It's implemented using a list internally, effectively - so instead of looking up by hash code, it does a binary search. SortedDictionary
is similarly based on binary searches, but via a tree instead of a list.
这篇关于根据键对字典进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!