按字母排序字典 [英] Sorting a Dictionary in place with respect to keys

查看:186
本文介绍了按字母排序字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在C#中有一个字典,如

I have a dictionary in C# like

Dictionary<Person, int>

我想将该字典排除在 类中的一个字段)。我该怎么做?互联网上的每一个可用的帮助都是列表,没有特定的字典排序的例子。任何帮助将非常感谢!

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!

推荐答案

您不能排序字典&TK。,TValue> - 它本来是无序的。 (或者说,检索条目的顺序是实现特定的,您不应该依赖于在版本之间的相同方式,因为排序不是其设计功能的一部分。)

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< TKey,TValue> SortedDictionary< TKey,TValue> ,两者都按键排列(以可配置的方式,如果您通过一个 IEqualityComparer< T> 到构造函数中) - 这可能对你有用吗?

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.

这篇关于按字母排序字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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