SortedList(Of TKey, TValue) Constructor ()

 

Initializes a new instance of the SortedList(Of TKey, TValue) class that is empty, has the default initial capacity, and uses the default IComparer(Of T).

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

Public Sub New

Every key in a SortedList(Of TKey, TValue) must be unique according to the default comparer.

This constructor uses the default value for the initial capacity of the SortedList(Of TKey, TValue). To set the initial capacity, use the SortedList(Of TKey, TValue)(Int32) constructor. If the final size of the collection can be estimated, specifying the initial capacity eliminates the need to perform a number of resizing operations while adding elements to the SortedList(Of TKey, TValue).

This constructor uses the default comparer for TKey. To specify a comparer, use the SortedList(Of TKey, TValue)(IComparer(Of TKey)) constructor. The default comparer Comparer(Of T).Default checks whether the key type TKey implements System.IComparable(Of T) and uses that implementation, if available. If not, Comparer(Of T).Default checks whether the key type TKey implements System.IComparable. If the key type TKey does not implement either interface, you can specify a System.Collections.Generic.IComparer(Of T) implementation in a constructor overload that accepts a comparer parameter.

This constructor is an O(1) operation.

The following code example creates an empty SortedList(Of TKey, TValue) 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.

This code example is part of a larger example provided for the SortedList(Of TKey, TValue) class.

' Create a new sorted list of strings, with string 
' keys. 
Dim openWith As New SortedList(Of String, String)

' Add some elements to the list. 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 list.
Try
    openWith.Add("txt", "winword.exe")
Catch 
    Console.WriteLine("An element with Key = ""txt"" already exists.")
End Try

Universal Windows Platform
Available since 10
.NET Framework
Available since 2.0
Return to top
Show: