C# 反转字典中的项目

发布于 2024-09-11 23:16:28 字数 265 浏览 2 评论 0原文

我正在尝试用 C# 反转字典中的项目。 我尝试过:

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

但是, dict.Reverse() 给了我一种 IEnumberable> 类型。我只是想知道如何才能将其变成一种字典?

提前致谢。

I'm trying to reverse items in a dictionary in 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>. I was just wondering how I could make it to a type of Dictionary?

Thanks in advance.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

忘年祭陌 2024-09-18 23:16:28

停止!

字典、哈希表和集合没有顺序。

排序或更改顺序绝对没有意义。

Stop!

Dictionaries and hashtables and sets have no ordering.

There is absolutely no point in sorting or changing the order.

找个人就嫁了吧 2024-09-18 23:16:28

字典不是有序的数据结构。要使 Reverse 具有任何实际意义,您需要使用 SortedDictionary。您可以通过使用比较器创建一个新的 SortedDictionary 来获取 SortedDictionary 的反向副本,该比较器执行与原始排序相反的排序(请参阅 构造函数)。

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

请注意,ReverseKeyComparer 是示例中的虚构类。

另外 - 如果您将 Dictionary 等同于 maphashtable,那么您需要知道 SortedDictionary 有点用词不当。它使用二叉树实现(我认为是红黑),其算法复杂度与 Dictionary 的哈希表实现不同。请参阅各自文档页面的备注部分。如果性能至关重要,您可能需要考虑顺序是否真正重要。

A Dictionary isn't an ordered data structure. For Reverse to have any real meaning you'll need to use a 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).

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

Note that ReverseKeyComparer is a ficticious class for the example.

Also - you need to know that the SortedDictionary is somewhat of a misnomer, if you equate Dictionary to map or hashtable. It uses a binary tree implementation (Red-Black, I think) with different algorithmic complexity than the hashtable implementation of 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.

盗琴音 2024-09-18 23:16:28

如果您希望字典具有一定的顺序,您应该查看 SortedDictionary。
请参阅本文。

If you want dictionaries to have a certain order, you should look into SortedDictionary.
See this article.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文