SortedList<TKey, TValue> Constructor (Int32)
Initializes a new instance of the SortedList<TKey, TValue> class that is empty, has the specified initial capacity, and uses the default IComparer<T>.
Assembly: System (in System.dll)
Parameters
- capacity
-
Type:
System.Int32
The initial number of elements that the SortedList<TKey, TValue> can contain.
| Exception | Condition |
|---|---|
| ArgumentOutOfRangeException | capacity is less than zero. |
Every key in a SortedList<TKey, TValue> must be unique according to the default comparer.
The capacity of a SortedList<TKey, TValue> is the number of elements that the SortedList<TKey, TValue> can hold before resizing. As elements are added to a SortedList<TKey, TValue>, the capacity is automatically increased as required by reallocating the internal array.
If the 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>.
The capacity can be decreased by calling TrimExcess or by setting the Capacity property explicitly. Decreasing the capacity reallocates memory and copies all the elements in the SortedList<TKey, TValue>.
This constructor uses the default comparer for TKey. To specify a comparer, use the SortedList<TKey, TValue>(Int32, IComparer<TKey>) constructor. The default comparer Comparer<T>.Default checks whether the key type TKey implements System.IComparable<T> and uses that implementation, if available. If not, Comparer<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<T> implementation in a constructor overload that accepts a comparer parameter.
This constructor is an O(n) operation, where n is capacity.
The following code example creates a sorted list with an initial capacity of 4 and populates it with 4 entries.
using System; using System.Collections.Generic; public class Example { public static void Main() { // Create a new sorted list of strings, with string keys and // an initial capacity of 4. SortedList<string, string> openWith = new SortedList<string, string>(4); // Add 4 elements to the list. openWith.Add("txt", "notepad.exe"); openWith.Add("bmp", "paint.exe"); openWith.Add("dib", "paint.exe"); openWith.Add("rtf", "wordpad.exe"); // List the contents of the sorted list. 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: 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