SortedList(Of TKey, TValue) Constructor (IComparer(Of TKey))
Initializes a new instance of the SortedList(Of TKey, TValue) class that is empty, has the default initial capacity, and uses the specified IComparer(Of T).
Assembly: System (in System.dll)
Parameters
- comparer
-
Type:
System.Collections.Generic.IComparer(Of TKey)
The IComparer(Of T) implementation to use when comparing keys.
-or-
null to use the default Comparer(Of T) for the type of the key.
Every key in a SortedList(Of TKey, TValue) must be unique according to the specified 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, IComparer(Of TKey)) 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 is an O(1) operation.
The following code example creates a sorted list with a case-insensitive comparer for the current culture. The example adds four elements, some with lower-case keys and some with upper-case keys. The example then attempts to add an element with a key that differs from an existing key only by case, catches the resulting exception, and displays an error message. Finally, the example displays the elements in case-insensitive sort order.
Imports System Imports System.Collections.Generic Public Class Example Public Shared Sub Main() ' Create a new sorted list of strings, with string keys and ' a case-insensitive comparer for the current culture. Dim openWith As New SortedList(Of String, String)( _ StringComparer.CurrentCultureIgnoreCase) ' Add some elements to the list. openWith.Add("txt", "notepad.exe") openWith.Add("bmp", "paint.exe") openWith.Add("DIB", "paint.exe") openWith.Add("rtf", "wordpad.exe") ' Try to add a fifth element with a key that is the same ' except for case; this would be allowed with the default ' comparer. Try openWith.Add("BMP", "paint.exe") Catch ex As ArgumentException Console.WriteLine(vbLf & "BMP is already in the sorted list.") End Try ' List the contents of the sorted list. Console.WriteLine() For Each kvp As KeyValuePair(Of String, String) In openWith Console.WriteLine("Key = {0}, Value = {1}", _ kvp.Key, kvp.Value) Next kvp End Sub End Class ' This code example produces the following output: ' 'BMP is already in the sorted list. ' 'Key = bmp, Value = paint.exe 'Key = DIB, Value = paint.exe 'Key = rtf, Value = wordpad.exe 'Key = txt, Value = notepad.exe
Available since 10
.NET Framework
Available since 2.0