SortedDictionary 제네릭 클래스
어셈블리: System(system.dll)
SortedDictionary 제네릭 클래스는 O(log n) 검색 기능을 사용하는 이진 검색 트리입니다. 여기서 n은 사전의 요소 수입니다. 이런 점에서 이 클래스는 SortedList 제네릭 클래스와 유사합니다. 이 두 클래스는 유사한 개체 모델을 가지고 있고 둘 다 O(log n) 검색 기능을 사용합니다. 이 두 클래스가 다른 점은 다음과 같이 메모리 사용량과 삽입 및 제거 작업의 속도입니다.
-
SortedList는 SortedDictionary보다 메모리를 적게 사용합니다.
-
SortedDictionary는 O(log n)를 사용하여 정렬되지 않은 데이터에 대해 보다 빠른 삽입 및 제거 작업을 수행하는 반면 SortedList는 O(n)를 사용합니다.
-
목록이 정렬된 데이터로 한 번에 채워지는 경우 SortedList는 SortedDictionary보다 빠릅니다.
각 키/값 쌍은 KeyValuePair 구조체 형식으로 검색하거나, 제네릭이 아닌 IDictionary 인터페이스를 통해 DictionaryEntry 형식으로 검색할 수 있습니다.
SortedDictionary에서 키로 사용하는 동안에는 해당 키를 변경하지 않아야 합니다. SortedDictionary의 모든 키는 고유해야 합니다. 키는 Null 참조(Visual Basic의 경우 Nothing)이 될 수 없습니다. 그러나 TValue가 참조 형식인 경우 값은 null이 될 수 있습니다.
SortedDictionary에는 키 비교를 수행하기 위한 비교자 구현이 필요합니다. comparer 매개 변수를 허용하는 생성자를 사용하여 IComparer 제네릭 인터페이스의 구현을 지정할 수 있지만 구현을 지정하지 않으면 기본 제네릭 비교자인 Comparer.Default가 사용됩니다. TKey 형식이 System.IComparable 제네릭 인터페이스를 구현하는 경우 기본 비교자가 해당 구현을 사용합니다.
C# 언어의 foreach 문(C++의 경우 for each, Visual Basic의 경우 For Each)은 컬렉션에 있는 각 요소의 형식을 필요로 합니다. SortedDictionary의 각 요소가 키/값 쌍이므로 요소 형식은 키의 형식도, 값의 형식도 아닙니다. 대신 요소 형식은 KeyValuePair입니다. 다음 코드에서는 C#, C++ 및 Visual Basic 구문을 보여 줍니다.
foreach 문은 열거자를 둘러싸는 래퍼로, 컬렉션에서 읽기만 가능하고 컬렉션에 쓰는 것은 허용되지 않습니다.
다음 코드 예제에서는 문자열 키를 사용하여 문자열의 빈 SortedDictionary를 만들고 Add 메서드를 사용하여 몇 가지 요소를 추가합니다. 이 예제에서는 중복 키를 추가하려고 하면 Add 메서드가 ArgumentException을 throw하는 것을 보여 줍니다.
예제에서는 Item 속성(C#의 경우 인덱서)을 사용하여 값을 검색하며, 요청된 키가 없으면 KeyNotFoundException이 throw되는 것과 키와 연결된 값을 바꾸는 방법을 보여 줍니다.
예제에서는 프로그램에서 사전에 없는 키 값을 자주 사용해야 하는 경우 값을 검색하는 더욱 효율적인 방법으로 TryGetValue 메서드를 사용하는 방법과 ContainsKey 메서드를 사용하여 Add 메서드를 호출하기 전에 키가 있는지 여부를 확인하는 방법을 보여 줍니다.
이 예제에서는 사전에 있는 키와 값을 열거하는 방법과 Keys 속성 및 Values 속성을 사용하여 키 및 값만 열거하는 방법을 보여 줍니다.
마지막으로 이 예제에서는 Remove 메서드를 사용하는 방법을 보여 줍니다.
using System; using System.Collections.Generic; public class Example { public static void Main() { // Create a new dictionary of strings, with string keys. // Dictionary<string, string> openWith = new Dictionary<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. Dictionary<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. Dictionary<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 = txt, Value = notepad.exe Key = bmp, Value = paint.exe Key = dib, Value = paint.exe Key = rtf, Value = winword.exe Key = doc, Value = winword.exe Key = ht, Value = hypertrm.exe Value = notepad.exe Value = paint.exe Value = paint.exe Value = winword.exe Value = winword.exe Value = hypertrm.exe Key = txt Key = bmp Key = dib Key = rtf Key = doc Key = ht Remove("doc") Key "doc" is not found. */
이 형식의 public static(Visual Basic의 경우 Shared) 멤버는 스레드로부터 안전합니다. 모든 인스턴스 멤버는 스레드로부터 안전하지 않을 수 있습니다.
SortedDictionary는 컬렉션이 수정되지 않으면 여러 개의 reader를 동시에 지원할 수 있습니다. 그렇다 하더라도 컬렉션을 열거하는 프로시저는 기본적으로 스레드로부터 안전하지 않습니다. 열거하는 동안 스레드로부터 안전하게 보호하려면 열거하는 동안 컬렉션을 잠글 수 있습니다. 여러 스레드에서 컬렉션에 액세스하여 읽고 쓸 수 있도록 허용하려면 사용자 지정 동기화를 구현해야 합니다.
Windows 98, Windows 2000 SP4, Windows Millennium Edition, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition
.NET Framework에서 모든 플래폼의 모든 버전을 지원하지는 않습니다. 지원되는 버전의 목록은 시스템 요구 사항을 참조하십시오.