SortedDictionary<TKey, TValue> Constructor (IComparer<TKey>)
Initializes a new instance of the SortedDictionary<TKey, TValue> class that is empty and uses the specified IComparer<T> implementation to compare keys.
Assembly: System (in System.dll)
Parameters
- comparer
-
Type:
System.Collections.Generic.IComparer<TKey>
The IComparer<T> implementation to use when comparing keys, or null to use the default Comparer<T> for the type of the key.
Every key in a SortedDictionary<TKey, TValue> must be unique according to the specified comparer.
SortedDictionary<TKey, TValue> requires a comparer implementation to perform key comparisons. If comparer is null, this constructor uses the default generic equality comparer, Comparer<T>.Default. If type TKey implements the System.IComparable<T> generic interface, the default comparer uses that implementation.
This constructor is an O(1) operation.
The following code example creates a SortedDictionary<TKey, TValue> 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.
using System; using System.Collections.Generic; public class Example { public static void Main() { // Create a new SortedDictionary of strings, with string keys // and a case-insensitive comparer for the current culture. SortedDictionary<string, string> openWith = new SortedDictionary<string, string>( StringComparer.CurrentCultureIgnoreCase); // Add some elements to the dictionary. 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 (ArgumentException) { Console.WriteLine("\nBMP is already in the dictionary."); } // List the contents of the sorted dictionary. Console.WriteLine(); foreach( KeyValuePair<string, string> kvp in openWith ) { Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value); } } } /* This code example produces the following output: BMP is already in the dictionary. Key = bmp, Value = paint.exe Key = DIB, Value = paint.exe Key = rtf, Value = wordpad.exe Key = txt, Value = notepad.exe */
Available since 8
.NET Framework
Available since 2.0
Portable Class Library
Supported in: portable .NET platforms
Windows Phone Silverlight
Available since 8.0
Windows Phone
Available since 8.1