.NET Framework Class Library
SortedList Class

Represents a collection of key/value pairs that are sorted by the keys and are accessible by key and by index.

Inheritance Hierarchy
SystemObject
  System.CollectionsSortedList

Namespace:   System.Collections
Assembly:  mscorlib (in mscorlib.dll)
Syntax
<[%$TOPIC/w1xa3kh1_en-us_VS_110_2_0_0_0_0%]> _
<[%$TOPIC/w1xa3kh1_en-us_VS_110_2_0_0_0_1%](True)> _
Public Class SortedList _
	Implements [%$TOPIC/w1xa3kh1_en-us_VS_110_2_0_0_0_2%], [%$TOPIC/w1xa3kh1_en-us_VS_110_2_0_0_0_3%], [%$TOPIC/w1xa3kh1_en-us_VS_110_2_0_0_0_4%], [%$TOPIC/w1xa3kh1_en-us_VS_110_2_0_0_0_5%]
[[%$TOPIC/w1xa3kh1_en-us_VS_110_2_0_1_0_0%]]
[[%$TOPIC/w1xa3kh1_en-us_VS_110_2_0_1_0_1%](true)]
public class SortedList : [%$TOPIC/w1xa3kh1_en-us_VS_110_2_0_1_0_2%], [%$TOPIC/w1xa3kh1_en-us_VS_110_2_0_1_0_3%], 
	[%$TOPIC/w1xa3kh1_en-us_VS_110_2_0_1_0_4%], [%$TOPIC/w1xa3kh1_en-us_VS_110_2_0_1_0_5%]
[[%$TOPIC/w1xa3kh1_en-us_VS_110_2_0_2_0_0%]]
[[%$TOPIC/w1xa3kh1_en-us_VS_110_2_0_2_0_1%](true)]
public ref class SortedList : [%$TOPIC/w1xa3kh1_en-us_VS_110_2_0_2_0_2%], 
	[%$TOPIC/w1xa3kh1_en-us_VS_110_2_0_2_0_3%], [%$TOPIC/w1xa3kh1_en-us_VS_110_2_0_2_0_4%], [%$TOPIC/w1xa3kh1_en-us_VS_110_2_0_2_0_5%]
[<[%$TOPIC/w1xa3kh1_en-us_VS_110_2_0_3_0_0%]>]
[<[%$TOPIC/w1xa3kh1_en-us_VS_110_2_0_3_0_1%](true)>]
type SortedList =  
    class 
        interface [%$TOPIC/w1xa3kh1_en-us_VS_110_2_0_3_0_2%] 
        interface [%$TOPIC/w1xa3kh1_en-us_VS_110_2_0_3_0_3%] 
        interface [%$TOPIC/w1xa3kh1_en-us_VS_110_2_0_3_0_4%] 
        interface [%$TOPIC/w1xa3kh1_en-us_VS_110_2_0_3_0_5%] 
    end

The SortedList type exposes the following members.

Constructors
  NameDescription
Public method Supported by the XNA Framework SortedListInitializes a new instance of the SortedList class that is empty, has the default initial capacity, and is sorted according to the IComparable interface implemented by each key added to the SortedList object.
Public method Supported by the XNA Framework SortedList(IComparer)Initializes a new instance of the SortedList class that is empty, has the default initial capacity, and is sorted according to the specified IComparer interface.
Public method Supported by the XNA Framework SortedList(IDictionary)Initializes a new instance of the SortedList class that contains elements copied from the specified dictionary, has the same initial capacity as the number of elements copied, and is sorted according to the IComparable interface implemented by each key.
Public method Supported by the XNA Framework SortedList(Int32)Initializes a new instance of the SortedList class that is empty, has the specified initial capacity, and is sorted according to the IComparable interface implemented by each key added to the SortedList object.
Public method Supported by the XNA Framework SortedList(IComparer, Int32)Initializes a new instance of the SortedList class that is empty, has the specified initial capacity, and is sorted according to the specified IComparer interface.
Public method Supported by the XNA Framework SortedList(IDictionary, IComparer)Initializes a new instance of the SortedList class that contains elements copied from the specified dictionary, has the same initial capacity as the number of elements copied, and is sorted according to the specified IComparer interface.
Top
Properties
  NameDescription
Public property Supported by the XNA Framework CapacityGets or sets the capacity of a SortedList object.
Public property Supported by the XNA Framework CountGets the number of elements contained in a SortedList object.
Public property Supported by the XNA Framework IsFixedSizeGets a value indicating whether a SortedList object has a fixed size.
Public property Supported by the XNA Framework IsReadOnlyGets a value indicating whether a SortedList object is read-only.
Public property Supported by the XNA Framework IsSynchronizedGets a value indicating whether access to a SortedList object is synchronized (thread safe).
Public property Supported by the XNA Framework ItemGets and sets the value associated with a specific key in a SortedList object.
Public property Supported by the XNA Framework KeysGets the keys in a SortedList object.
Public property Supported by the XNA Framework SyncRootGets an object that can be used to synchronize access to a SortedList object.
Public property Supported by the XNA Framework ValuesGets the values in a SortedList object.
Top
Methods
  NameDescription
Public method Supported by the XNA Framework AddAdds an element with the specified key and value to a SortedList object.
Public method Supported by the XNA Framework ClearRemoves all elements from a SortedList object.
Public method Supported by the XNA Framework CloneCreates a shallow copy of a SortedList object.
Public method Supported by the XNA Framework ContainsDetermines whether a SortedList object contains a specific key.
Public method Supported by the XNA Framework ContainsKeyDetermines whether a SortedList object contains a specific key.
Public method Supported by the XNA Framework ContainsValueDetermines whether a SortedList object contains a specific value.
Public method Supported by the XNA Framework CopyToCopies SortedList elements to a one-dimensional Array object, starting at the specified index in the array.
Public method Supported by the XNA Framework Equals(Object)Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method Supported by the XNA Framework FinalizeAllows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method Supported by the XNA Framework GetByIndexGets the value at the specified index of a SortedList object.
Public method Supported by the XNA Framework GetEnumeratorReturns an IDictionaryEnumerator object that iterates through a SortedList object.
Public method Supported by the XNA Framework GetHashCodeServes as the default hash function. (Inherited from Object.)
Public method Supported by the XNA Framework GetKeyGets the key at the specified index of a SortedList object.
Public method Supported by the XNA Framework GetKeyListGets the keys in a SortedList object.
Public method Supported by the XNA Framework GetTypeGets the Type of the current instance. (Inherited from Object.)
Public method Supported by the XNA Framework GetValueListGets the values in a SortedList object.
Public method Supported by the XNA Framework IndexOfKeyReturns the zero-based index of the specified key in a SortedList object.
Public method Supported by the XNA Framework IndexOfValueReturns the zero-based index of the first occurrence of the specified value in a SortedList object.
Protected method Supported by the XNA Framework MemberwiseCloneCreates a shallow copy of the current Object. (Inherited from Object.)
Public method Supported by the XNA Framework RemoveRemoves the element with the specified key from a SortedList object.
Public method Supported by the XNA Framework RemoveAtRemoves the element at the specified index of a SortedList object.
Public method Supported by the XNA Framework SetByIndexReplaces the value at a specific index in a SortedList object.
Public method Static member Supported by the XNA Framework SynchronizedReturns a synchronized (thread-safe) wrapper for a SortedList object.
Public method Supported by the XNA Framework ToStringReturns a string that represents the current object. (Inherited from Object.)
Public method Supported by the XNA Framework TrimToSizeSets the capacity to the actual number of elements in a SortedList object.
Top
Extension Methods
  NameDescription
Public Extension Method AsParallelEnables parallelization of a query. (Defined by ParallelEnumerable.)
Public Extension Method AsQueryableConverts an IEnumerable to an IQueryable. (Defined by Queryable.)
Public Extension Method Supported by the XNA Framework CastTResultCasts the elements of an IEnumerable to the specified type. (Defined by Enumerable.)
Public Extension Method Supported by the XNA Framework OfTypeTResultFilters the elements of an IEnumerable based on a specified type. (Defined by Enumerable.)
Top
Explicit Interface Implementations
  NameDescription
Explicit interface implemetation Private method Supported by the XNA Framework IEnumerableGetEnumeratorReturns an IEnumerator that iterates through the SortedList.
Top
Remarks

For the generic version of this collection, see System.Collections.GenericSortedListTKey, TValue.

A SortedList element can be accessed by its key, like an element in any IDictionary implementation, or by its index, like an element in any IList implementation.

A SortedList object internally maintains two arrays to store the elements of the list; that is, one array for the keys and another array for the associated values. Each element is a key/value pair that can be accessed as a DictionaryEntry object. A key cannot be , but a value can be.

The capacity of a SortedList object is the number of elements the SortedList can hold. As elements are added to a SortedList, the capacity is automatically increased as required through reallocation. The capacity can be decreased by calling TrimToSize or by setting the Capacity property explicitly.

For very large SortedList objects, you can increase the maximum capacity to 2 billion elements on a 64-bit system by setting the enabled attribute of the gcAllowVeryLargeObjects configuration element to true in the run-time environment.

The elements of a SortedList object are sorted by the keys either according to a specific IComparer implementation specified when the SortedList is created or according to the IComparable implementation provided by the keys themselves. In either case, a SortedList does not allow duplicate keys.

The index sequence is based on the sort sequence. When an element is added, it is inserted into SortedList in the correct sort order, and the indexing adjusts accordingly. When an element is removed, the indexing also adjusts accordingly. Therefore, the index of a specific key/value pair might change as elements are added or removed from the SortedList object.

Operations on a SortedList object tend to be slower than operations on a Hashtable object because of the sorting. However, the SortedList offers more flexibility by allowing access to the values either through the associated keys or through the indexes.

Elements in this collection can be accessed using an integer index. Indexes in this collection are zero-based.

The foreach statement of the C# language (for each in Visual Basic) requires the type of each element in the collection. Since each element of the SortedList object is a key/value pair, the element type is not the type of the key or the type of the value. Rather, the element type is DictionaryEntry. For example:

For Each de As DictionaryEntry In mySortedList
    '... 
Next de
foreach (DictionaryEntry de in mySortedList)
{
    //...
}
for each (DictionaryEntry de in mySortedList)
{
    //...
}

The foreach statement is a wrapper around the enumerator, which allows only reading from, not writing to, the collection.

Examples

The following code example shows how to create and initialize a SortedList object and how to print out its keys and values.

Imports System
Imports System.Collections
Imports Microsoft.VisualBasic

Public Class SamplesSortedList    

    Public Shared Sub Main()

        ' Creates and initializes a new SortedList. 
        Dim mySL As New SortedList()
        mySL.Add("Third", "!")
        mySL.Add("Second", "World")
        mySL.Add("First", "Hello")

        ' Displays the properties and values of the SortedList.
        Console.WriteLine("mySL")
        Console.WriteLine("  Count:    {0}", mySL.Count)
        Console.WriteLine("  Capacity: {0}", mySL.Capacity)
        Console.WriteLine("  Keys and Values:")
        PrintKeysAndValues(mySL)
    End Sub 

    Public Shared Sub PrintKeysAndValues(myList As SortedList)
        Console.WriteLine(ControlChars.Tab & "-KEY-" & ControlChars.Tab & _
           "-VALUE-")
        Dim i As Integer 
        For i = 0 To myList.Count - 1
            Console.WriteLine(ControlChars.Tab & "{0}:" & ControlChars.Tab & _
               "{1}", myList.GetKey(i), myList.GetByIndex(i))
        Next i
        Console.WriteLine()
    End Sub 
End Class 

' This code produces the following output. 
'  
' mySL 
'   Count:    3 
'   Capacity: 16 
'   Keys and Values: 
'     -KEY-     -VALUE- 
'     First:    Hello 
'     Second:   World 
'     Third:    !
using System;
using System.Collections;
public class SamplesSortedList  {

   public static void Main()  {

      // Creates and initializes a new SortedList.
      SortedList mySL = new SortedList();
       mySL.Add("Third", "!");
       mySL.Add("Second", "World");
       mySL.Add("First", "Hello");

      // Displays the properties and values of the SortedList.
      Console.WriteLine( "mySL" );
      Console.WriteLine( "  Count:    {0}", mySL.Count );
      Console.WriteLine( "  Capacity: {0}", mySL.Capacity );
      Console.WriteLine( "  Keys and Values:" );
      PrintKeysAndValues( mySL );
   }


   public static void PrintKeysAndValues( SortedList myList )  {
      Console.WriteLine( "\t-KEY-\t-VALUE-" );
      for ( int i = 0; i < myList.Count; i++ )  {
         Console.WriteLine( "\t{0}:\t{1}", myList.GetKey(i), myList.GetByIndex(i) );
      }
      Console.WriteLine();
   }
}
/*
This code produces the following output.

mySL
  Count:    3
  Capacity: 16
  Keys and Values:
    -KEY-    -VALUE-
    First:    Hello
    Second:    World
    Third:    !
*/
#using <system.dll>

using namespace System;
using namespace System::Collections;
public ref class SamplesSortedList
{
public:
   static void PrintKeysAndValues( SortedList^ myList )
   {
      Console::WriteLine( "\t-KEY-\t-VALUE-" );
      for ( int i = 0; i < myList->Count; i++ )
      {
         Console::WriteLine( "\t{0}:\t{1}", myList->GetKey( i ), myList->GetByIndex( i ) );

      }
      Console::WriteLine();
   }

};

int main()
{

   // Creates and initializes a new SortedList.
   SortedList^ mySL = gcnew SortedList;
   mySL->Add( "Third", "!" );
   mySL->Add( "Second", "World" );
   mySL->Add( "First", "Hello" );

   // Displays the properties and values of the SortedList.
   Console::WriteLine( "mySL" );
   Console::WriteLine( "  Count:    {0}", mySL->Count );
   Console::WriteLine( "  Capacity: {0}", mySL->Capacity );
   Console::WriteLine( "  Keys and Values:" );
   SamplesSortedList::PrintKeysAndValues( mySL );
}

/*
This code produces the following output.

mySL
Count:    3
Capacity: 16
Keys and Values:
-KEY-    -VALUE-
First:    Hello
Second:    World
Third:    !
*/
Version Information

.NET Framework

Supported in: 4.5.2, 4.5.1, 4.5, 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1
Platforms

Windows 8.1, Windows Server 2012 R2, Windows 8, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role supported with SP1 or later; Itanium not supported)

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

Thread Safety

Public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

A SortedList object can support multiple readers concurrently, as long as the collection is not modified. To guarantee the thread safety of the SortedList, all operations must be done through the wrapper returned by the Synchronized method.

Enumerating through a collection is intrinsically not a thread-safe procedure. Even when a collection is synchronized, other threads can still modify the collection, which causes the enumerator to throw an exception. To guarantee thread safety during enumeration, you can either lock the collection during the entire enumeration or catch the exceptions resulting from changes made by other threads.