SortedDictionary

SortedDictionary 泛型類別是使用 O(log n) 擷取的二進位搜尋樹狀目錄,其中 n 為字典中的項目數目。在這個方面,它類似於 SortedList 泛型類別。這兩個類別具有類似的物件模型 (Object Model),且都具有 O(log n) 擷取。這兩個類別的不同之處在於,插入和移除的記憶體使用和速度:

  • SortedList 使用的記憶體少於 SortedDictionary

  • 對於未排序的資料,SortedDictionary 具有更快的插入和移除操作:對於 SortedList 使用 O(log n),而不是 O(n)。

  • 如果從排序的資料一次全部填入清單,則 SortedList 快於 SortedDictionary

每個索引鍵/值可以透過非泛型 IDictionary 介面,當做 KeyValuePair 結構或當做 DictionaryEntry 來進行擷取。

只要索引鍵在 SortedDictionary 中用做索引鍵,索引鍵就必須是不變的。在 SortedDictionary 中的每個索引鍵都必須是唯一的。索引鍵不能是 Null 參照 (即 Visual Basic 中的 Nothing),但是,如果值型別 TValue 是參考型別時,值就可以是 Null。

SortedDictionary 需要比較子實作,以執行索引鍵比較。藉由使用接受 comparer 參數的建構函式 (Constructor),您可以指定 IComparer 泛型介面的實作。如果您沒有指定實作,則會使用預設的泛型比較子 Comparer.Default。如果型別 TKey 會實作System.IComparable 泛型介面,則預設比較子會使用該實作。

using System;
using System.Collections.Generic;

public class Example
{
    public static void Main()
    {
        // Create a new sorted dictionary of strings, with string
        // keys.
        SortedDictionary<string, string> openWith = 
            new SortedDictionary<string, string>();

        // Add some elements to the dictionary. There are no 
        // duplicate keys, but some of the values are duplicates.
        openWith.Add("txt", "notepad.exe");
        openWith.Add("bmp", "paint.exe");
        openWith.Add("dib", "paint.exe");
        openWith.Add("rtf", "wordpad.exe");

        // The Add method throws an exception if the new key is 
        // already in the dictionary.
        try
        {
            openWith.Add("txt", "winword.exe");
        }
        catch (ArgumentException)
        {
            Console.WriteLine("An element with Key = \"txt\" already exists.");
        }

        // The Item property is another name for the indexer, so you 
        // can omit its name when accessing elements. 
        Console.WriteLine("For key = \"rtf\", value = {0}.", 
            openWith["rtf"]);

        // The indexer can be used to change the value associated
        // with a key.
        openWith["rtf"] = "winword.exe";
        Console.WriteLine("For key = \"rtf\", value = {0}.", 
            openWith["rtf"]);

        // If a key does not exist, setting the indexer for that key
        // adds a new key/value pair.
        openWith["doc"] = "winword.exe";

        // The indexer throws an exception if the requested key is
        // not in the dictionary.
        try
        {
            Console.WriteLine("For key = \"tif\", value = {0}.", 
                openWith["tif"]);
        }
        catch (KeyNotFoundException)
        {
            Console.WriteLine("Key = \"tif\" is not found.");
        }

        // When a program often has to try keys that turn out not to
        // be in the dictionary, TryGetValue can be a more efficient 
        // way to retrieve values.
        string value = "";
        if (openWith.TryGetValue("tif", out value))
        {
            Console.WriteLine("For key = \"tif\", value = {0}.", value);
        }
        else
        {
            Console.WriteLine("Key = \"tif\" is not found.");
        }

        // ContainsKey can be used to test keys before inserting 
        // them.
        if (!openWith.ContainsKey("ht"))
        {
            openWith.Add("ht", "hypertrm.exe");
            Console.WriteLine("Value added for key = \"ht\": {0}", 
                openWith["ht"]);
        }

        // When you use foreach to enumerate dictionary elements,
        // the elements are retrieved as KeyValuePair objects.
        Console.WriteLine();
        foreach( KeyValuePair<string, string> kvp in openWith )
        {
            Console.WriteLine("Key = {0}, Value = {1}", 
                kvp.Key, kvp.Value);
        }

        // To get the values alone, use the Values property.
        SortedDictionary<string, string>.ValueCollection valueColl = 
            openWith.Values;

        // The elements of the ValueCollection are strongly typed
        // with the type that was specified for dictionary values.
        Console.WriteLine();
        foreach( string s in valueColl )
        {
            Console.WriteLine("Value = {0}", s);
        }

        // To get the keys alone, use the Keys property.
        SortedDictionary<string, string>.KeyCollection keyColl = 
            openWith.Keys;

        // The elements of the KeyCollection are strongly typed
        // with the type that was specified for dictionary keys.
        Console.WriteLine();
        foreach( string s in keyColl )
        {
            Console.WriteLine("Key = {0}", s);
        }

        // Use the Remove method to remove a key/value pair.
        Console.WriteLine("\nRemove(\"doc\")");
        openWith.Remove("doc");

        if (!openWith.ContainsKey("doc"))
        {
            Console.WriteLine("Key \"doc\" is not found.");
        }
    }
}

/* This code example produces the following output:

An element with Key = "txt" already exists.
For key = "rtf", value = wordpad.exe.
For key = "rtf", value = winword.exe.
Key = "tif" is not found.
Key = "tif" is not found.
Value added for key = "ht": hypertrm.exe

Key = bmp, Value = paint.exe
Key = dib, Value = paint.exe
Key = doc, Value = winword.exe
Key = ht, Value = hypertrm.exe
Key = rtf, Value = winword.exe
Key = txt, Value = notepad.exe

Value = paint.exe
Value = paint.exe
Value = winword.exe
Value = hypertrm.exe
Value = winword.exe
Value = notepad.exe

Key = bmp
Key = dib
Key = doc
Key = ht
Key = rtf
Key = txt

Remove("doc")
Key "doc" is not found.
 */

System.Collections.SortedList 类、System.Collections.Generic.SortedList 泛型类和 System.Collections.Generic.SortedDictionary 泛型类类似于 Hashtable 类和 Dictionary 泛型类,因为它们也实现 IDictionary 接口,但是它们以基于键的排序顺序维护元素,没有哈希表的 O(1) 插入和检索特性。这三个类具有若干共性:

 
  • 三个类都实现 System.Collections.IDictionary 接口。两个泛型类还实现 System.Collections.Generic.IDictionary 泛型接口。

  • 每个元素是一个键/值对,以进行枚举。

    Note注意

    非泛型 SortedList 类在被枚举时返回 DictionaryEntry 对象,而两个泛型类则返回 KeyValuePair 对象。

  • 元素按照 System.Collections.IComparer 实现(对于非泛型 SortedList)或 System.Collections.Generic.IComparer 实现(对于两个泛型类)排序。

  • 每个类提供了返回仅包含键或仅包含值的集合的属性。

下表列举两个排序的列表类与 SortedDictionary 类之间的一些区别。

SortedList 非泛型类和 SortedList 泛型类 SortedDictionary 泛型类

返回键和值的属性是有索引的,从而允许高效的索引检索。

无索引的检索。

检索的运算复杂度为 O(log n)。

检索的运算复杂度为 O(log n)。

插入和移除的运算复杂度一般为 O(n);但是,对于已经处于排序顺序的数据,插入操作的运算复杂度为 O(1),因此每个元素都被添加到列表的末尾。(这假设不需要调整大小。)

插入和移除的运算复杂度为 O(log n)。

SortedDictionary 使用更少的内存。

SortedList 非泛型类和 SortedList 泛型类使用更多内存。

Note注意

对于包含自己的键的值(例如,包含雇员 ID 编号的雇员记录),可以通过从 KeyedCollection 泛型类派生创建带键的集合,该集合具有列表的一些特征和字典的一些特征。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值