SortedDictionary Generic Class

Represents a collection of key/value pairs that are sorted on the key.

Namespace: System.Collections.Generic
Assembly: System (in system.dll)

<SerializableAttribute> _
Public Class SortedDictionary(Of TKey, TValue)
	Implements IDictionary(Of TKey, TValue), ICollection(Of KeyValuePair(Of TKey, TValue)), _
	IEnumerable(Of KeyValuePair(Of TKey, TValue)), IDictionary, ICollection, _
Dim instance As SortedDictionary(Of TKey, TValue)

J# supports the use of generic types and methods, but not the declaration of new ones.
JScript does not support generic types and methods.
Not applicable.

Type Parameters


The type of the keys in the dictionary.


The type of the values in the dictionary.

The SortedDictionary generic class is a binary search tree with O(log n) retrieval, where n is the number of elements in the dictionary. In this respect, it is similar to the SortedList generic class. The two classes have similar object models, and both have O(log n) retrieval. Where the two classes differ is in memory use and speed of insertion and removal:

  • SortedList uses less memory than SortedDictionary.

  • SortedDictionary has faster insertion and removal operations for unsorted data: O(log n) as opposed to O(n) for SortedList.

  • If the list is populated all at once from sorted data, SortedList is faster than SortedDictionary.

Each key/value pair can be retrieved as a KeyValuePair structure, or as a DictionaryEntry through the nongeneric IDictionary interface.

Keys must be immutable as long as they are used as keys in the SortedDictionary. Every key in a SortedDictionary must be unique. A key cannot be a null reference (Nothing in Visual Basic), but a value can be, if the value type TValue is a reference type.

SortedDictionary requires a comparer implementation to perform key comparisons. You can specify an implementation of the IComparer generic interface by using a constructor that accepts a comparer parameter; if you do not specify an implementation, the default generic comparer Comparer.Default is used. If type TKey implements the System.IComparable generic interface, the default comparer uses that implementation.

The foreach statement of the C# language (for each in C++, For Each in Visual Basic) requires the type of each element in the collection. Since each element of the SortedDictionary is a key/value pair, the element type is not the type of the key or the type of the value. Instead, the element type is KeyValuePair. The following code shows C#, C++, and Visual Basic syntax.

For Each kvp As KeyValuePair(Of Integer, String) In myDictionary
Next myKVP

The foreach statement is a wrapper around the enumerator, which allows only reading from the collection, not writing to it.

The following code example creates an empty SortedDictionary of strings with string keys and uses the Add method to add some elements. The example demonstrates that the Add method throws an ArgumentException when attempting to add a duplicate key.

The example uses the Item property (the indexer in C#) to retrieve values, demonstrating that a KeyNotFoundException is thrown when a requested key is not present, and showing that the value associated with a key can be replaced.

The example shows how to use the TryGetValue method as a more efficient way to retrieve values if a program often must try key values that are not in the dictionary, and it shows how to use the ContainsKey method to test whether a key exists before calling the Add method.

The example shows how to enumerate the keys and values in the dictionary and how to enumerate the keys and values alone using the Keys property and the Values property.

Finally, the example demonstrates the Remove method.

Imports System
Imports System.Collections.Generic

Public Class Example
    Public Shared Sub Main() 

        ' Create a new sorted dictionary of strings, with string 
        ' keys. 
        Dim openWith As New SortedDictionary(Of 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.
            openWith.Add("txt", "winword.exe")
            Console.WriteLine("An element with Key = ""txt"" already exists.")
        End Try

        ' The Item property is the default property, so you 
        ' can omit its name when accessing elements. 
        Console.WriteLine("For key = ""rtf"", value = {0}.", _
        ' The default Item property can be used to change the value
        ' associated with a key.
        openWith("rtf") = "winword.exe"
        Console.WriteLine("For key = ""rtf"", value = {0}.", _
        ' If a key does not exist, setting the default Item property
        ' for that key adds a new key/value pair.
        openWith("doc") = "winword.exe"

        ' The default Item property throws an exception if the requested
        ' key is not in the dictionary.
            Console.WriteLine("For key = ""tif"", value = {0}.", _
            Console.WriteLine("Key = ""tif"" is not found.")
        End Try

        ' 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.
        Dim value As String = ""
        If openWith.TryGetValue("tif", value) Then
            Console.WriteLine("For key = ""tif"", value = {0}.", value)
            Console.WriteLine("Key = ""tif"" is not found.")
        End If

        ' ContainsKey can be used to test keys before inserting 
        ' them.
        If Not openWith.ContainsKey("ht") Then
            openWith.Add("ht", "hypertrm.exe")
            Console.WriteLine("Value added for key = ""ht"": {0}", _
        End If

        ' When you use foreach to enumerate dictionary elements,
        ' the elements are retrieved as KeyValuePair objects.
        For Each kvp As KeyValuePair(Of String, String) In openWith
            Console.WriteLine("Key = {0}, Value = {1}", _
                kvp.Key, kvp.Value)
        Next kvp

        ' To get the values alone, use the Values property.
        Dim valueColl _
            As SortedDictionary(Of String, String).ValueCollection = _
        ' The elements of the ValueCollection are strongly typed
        ' with the type that was specified for dictionary values.
        For Each s As String In valueColl 
            Console.WriteLine("Value = {0}", s)
        Next s

        ' To get the keys alone, use the Keys property.
        Dim keyColl _
            As SortedDictionary(Of String, String).KeyCollection = _
        ' The elements of the KeyCollection are strongly typed
        ' with the type that was specified for dictionary keys.
        For Each s As String In keyColl 
            Console.WriteLine("Key = {0}", s)
        Next s

        ' Use the Remove method to remove a key/value pair.
        Console.WriteLine(vbLf + "Remove(""doc"")")
        If Not openWith.ContainsKey("doc") Then
            Console.WriteLine("Key ""doc"" is not found.")
        End If

    End Sub

End Class

' 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
'Key "doc" is not found.


Public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

A SortedDictionary can support multiple readers concurrently, as long as the collection is not modified. Even so, enumerating through a collection is intrinsically not a thread-safe procedure. To guarantee thread safety during enumeration, you can lock the collection during the entire enumeration. To allow the collection to be accessed by multiple threads for reading and writing, you must implement your own synchronization.

Windows 98, Windows Server 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

The Microsoft .NET Framework 3.0 is supported on Windows Vista, Microsoft Windows XP SP2, and Windows Server 2003 SP1.

.NET Framework

Supported in: 3.0, 2.0