SortedDictionary

对一个Dictionary<TKey, TValue>进行键排序能够直接用SortedDictionary
SortedDictionary<TKey, TValue> 泛型类是检索运算复杂度为 O(log n) 的二叉搜索树,其中 n 是字典中的元素数。 就这一点而言,它与 SortedList<TKey, TValue> 泛型类类似。 这两个类具备类似的对象模型,而且都具备 O(log n) 的检索运算复杂度。
这两个类的区别在于内存的使用以及插入和移除元素的速度:
SortedList<TKey, TValue> 使用的内存比 SortedDictionary<TKey, TValue> 少,SortedDictionary<TKey, TValue> 可对未排序的数据执行更快的插入和移除操做:
它的时间复杂度为 O(log n),而 SortedList<TKey,TValue> 为 O(n),若是使用排序数据一次性填充,SortedList<TKey,TValue>比 SortedDictionary<TKey, TValue> 快。
每一个键/值对均可以做为KeyValuePair<TKey, TValue> 结构进行检索,或做为DictionaryEntry经过非泛型IDictionary接口进行检索。只要键用做 SortedDictionary<TKey, TValue> 中的键,它们就必须是不可变的。
SortedDictionary<TKey, TValue> 中的每一个键必须是惟一的。 键不能为 null,可是若是值类型 TValue 为引用类型,该值则能够为空。
SortedDictionary<TKey, TValue> 须要比较器实现来执行键比较。 能够使用一个接受 comparer 参数的构造函数来指定 IComparer<T> 泛型接口的实现;
若是不指定实现,则使用默认的泛型比较器 Comparer<T>.Default。
若是类型 TKey 实现 System.IComparable<T> 泛型接口,则默认比较器使用该实现。
对一个Dictionary<TKey, TValue>进行值排序能够用LINQ:函数

Dictionary <string, string> MyDictionary = new Dictionary<string, string>();

MyDictionary = (from entry in MyDictionary
                                     orderby entry.Value ascending
                                     select entry).ToDictionary(pair => pair.Key, pair => pair.Value);
相关文章
相关标签/搜索