使用ToDictionary构建排序的字典 [英] Building a sorted dictionary using ToDictionary
问题描述
我有一个字典
,我明白一个哈希表,也就是键不排序。
dataBase = new Dictionary< string,Record>()
记录
是一个用户定义的类,的数据。
我发现一个有趣的例子,将这个字典
转换成由LINQ排序的字典:
var sortedDict =(从dataBase中的条目orderby entry.Key升序选择条目)
.ToDictionary(pair => pair.Key,pair => pair.Value);
此代码正常工作。
问题:我发现 sortedDict
c $ c> sortedDict 仍然是一个哈希表,一种类型:
System.Collections。 Generic.Dictionary< string,Record>
我预计结果字典应该是一种 map
如C ++ STL一样,通常以(平衡)二叉树的形式实现,以维护键的顺序。但是,由此产生的字典仍然是哈希表。
如何 sortedDict
可以维护排序吗?哈希表不能保存键的顺序。除了典型的哈希表外,是否执行C#的 Generic.Dictionary
维护两个数据结构:一个保持枚举的插入顺序的平面数组,以及按键检索的哈希表。
如果在排序集上使用 ToDictionary()
,枚举时将按顺序排列,但不会按顺序维护。任何新插入的项目将在枚举时添加到后面。
编辑:如果要依赖此行为,我建议您查看MSDN文档,以查看是否这是保证,或只是偶然的。
I'm not an expert in C# and LINQ.
I have a Dictionary
, which I understand a hash table, that is, keys are not sorted.
dataBase = new Dictionary<string, Record>()
Record
is a user-defined class that holds a number of data for a given key string.
I found an interesting example that converts this Dictionary
into a sorted dictionary by LINQ:
var sortedDict = (from entry in dataBase orderby entry.Key ascending select entry)
.ToDictionary(pair => pair.Key, pair => pair.Value);
This code works correctly. The resulting sortedDict
is sorted by keys.
Question: I found that sortedDict
is still a hash table, a type of:
System.Collections.Generic.Dictionary<string, Record>
I expected the resulting dictionary should be a sort of map
as in C++ STL, which is generally implemented as a (balanced) binary tree to maintain the ordering of the keys. However, the resulting dictionary is still a hash table.
How sortedDict
can maintain the ordering? A hash table can't hold the ordering of the keys. Is the implementation of C#'s Generic.Dictionary
other than a typical hash table?
Dictionary
maintains two data structures: a flat array that's kept in insertion order for enumeration, and the hash table for retrieval by key.
If you use ToDictionary()
on a sorted set, it will be in order when enumerated, but it won't be maintained in order. Any newly inserted items will be added to the back when enumerating.
Edit: If you want to rely on this behaviour, I would recommend looking at the MSDN docs to see if this is guaranteed, or just incidental.
这篇关于使用ToDictionary构建排序的字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!