C# Hashtable 按键排序
我有一个哈希表,其中包含字母键和数字值。 如何根据键对哈希表进行排序?
ExchangeA, 200
ExchangeV, 100
ExchangeC, 200
像这样
ExchangeA, 200
ExchangeC, 200
ExchangeV, 100
I have a hashtable with keys in alphabetic and values in numeric.
how to sort the hashtable based on keys?
ExchangeA, 200
ExchangeV, 100
ExchangeC, 200
to be like this
ExchangeA, 200
ExchangeC, 200
ExchangeV, 100
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您可以使用
SortedDictionary
来进行排序给你的钥匙。在您的情况下,SortedDictionary
可以工作:输出:
You can use a
SortedDictionary
for this which will do the sorting by key for you. In your case aSortedDictionary<string, int>
would work:Output:
我发现“排序”哈希表的最简单方法是:
但是,我没有对原始哈希表进行排序,只是以有序的方式读取其值。
正如在其他回复中一样,如果您需要以排序方式存储数据,最好是使用 SortedDictionary
The simplest way I found to "sort" hashtable is:
However, Im not ordering the original hashtable, only reading its values in an ordered way.
As in other replies, if you need to store your data is sorted way, the best is to use SortedDictionary
由于哈希表的性质,您无法在适当的键上对它们进行排序:它们根据哈希码将键组织在存储桶中,哈希码是哈希表控制之外的值。但是,您可以按照您喜欢的任何顺序读取键值对。以下是使用 LINQ 实现此操作的方法:
Because of the nature of hash tables, you cannot sort them on the key in place: they organize their keys in buckets based on their hash code, a value outside of hash table's control. However, you can read key-value pairs in whatever order that you like. Here is how you can do it using LINQ:
使用列表而不是哈希(或将哈希转换为字典),然后执行以下操作:
Use a list instead of a hash (or convert your hash to a dictionary), and do this:
使用 Linq 很简单(
使用 System.Linq
):返回一个
KeyValuePair
列表。Using Linq is easy (
using System.Linq
):That returns a list of
KeyValuePair<string, int>
.我使用一个列表来存储 Hashtable 的键并对它进行排序,然后使用这个排序列表显示 Hashtable。这是我的代码:
I used a list to store keys of Hashtable and sorted it and then dislayed Hashtable using this sorted list. Here is my code: