简体   繁体   English

C#反转词典中的项目

[英]C# Reverse items in Dictionary

I'm trying to reverse items in a dictionary in C#. 我正试图在C#中翻译字典中的项目。 I have tried: 我努力了:

Dictionary<double, int> dict = new Dictionary<double, int>();
...add itmes to it....
var v = dict.Reverse()

However, dict.Reverse() gives me a type of IEnumberable>. 但是,dict.Reverse()给了我一种IEnumberable>。 I was just wondering how I could make it to a type of Dictionary? 我只是想知道如何才能使它成为一种字典?

Thanks in advance. 提前致谢。

Stop! 停止!

Dictionaries and hashtables and sets have no ordering. 字典和哈希表和集合没有排序。

There is absolutely no point in sorting or changing the order. 排序或更改订单绝对没有意义。

A Dictionary isn't an ordered data structure. 字典不是有序数据结构。 For Reverse to have any real meaning you'll need to use a SortedDictionary. 要使Reverse具有任何实际意义,您需要使用SortedDictionary。 You can get a reversed copy of a SortedDictionary by creating a new one with a Comparer that does the opposite sorting to the original (see constructor ). 您可以通过创建一个带有Comparer的新副本来获得SortedDictionary的反向副本,该Comparer执行与原始相反的排序(请参阅构造函数 )。

var reversed = new SortedDictionary( original, new ReverseKeyComparer() );

Note that ReverseKeyComparer is a ficticious class for the example. 请注意, ReverseKeyComparer是该示例的一个ReverseKeyComparer类。

Also - you need to know that the SortedDictionary is somewhat of a misnomer, if you equate Dictionary to map or hashtable . 另外 - 如果你将Dictionary等同于maphashtable ,你需要知道SortedDictionary有点用词不当。 It uses a binary tree implementation (Red-Black, I think) with different algorithmic complexity than the hashtable implementation of Dictionary. 它使用二进制树实现(我认为是Red-Black),其算法复杂度不同于Dictionary的哈希表实现。 See the Remarks sections of their respective documentation pages. 请参阅各自文档页面的“备注”部分。 If performance is critical, you might want to consider whether the ordering is truly important. 如果性能至关重要,您可能需要考虑订购是否真正重要。

If you want dictionaries to have a certain order, you should look into SortedDictionary. 如果您希望字典具有特定顺序,则应查看SortedDictionary。 See this article. 看到这篇文章。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM