SortedList<TKey, TValue> Constructor (IComparer<TKey>)


The .NET API Reference documentation has a new home. Visit the .NET API Browser on to see the new experience.

Initializes a new instance of the SortedList<TKey, TValue> class that is empty, has the default initial capacity, and uses the specified IComparer<T>.

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

public SortedList(
	IComparer<TKey> comparer


Type: System.Collections.Generic.IComparer<TKey>

The IComparer<T> implementation to use when comparing keys.


null to use the default Comparer<T> for the type of the key.

Every key in a SortedList<TKey, TValue> must be unique according to the specified comparer.

This constructor uses the default value for the initial capacity of the SortedList<TKey, TValue>. To set the initial capacity, use the SortedList<TKey, TValue>(Int32, IComparer<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<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.

using System;
using System.Collections.Generic;

public class Example
    public static void Main()
        // Create a new sorted list of strings, with string keys and
        // a case-insensitive comparer for the current culture.
        SortedList<string, string> openWith = 
                      new SortedList<string, string>( 

        // 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.
            openWith.Add("BMP", "paint.exe");
        catch (ArgumentException)
            Console.WriteLine("\nBMP is already in the sorted list.");

        // List the contents of the sorted list.
        foreach( KeyValuePair<string, string> kvp in openWith )
            Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, 

/* 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

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