Export (0) Print
Expand All
6 out of 14 rated this helpful - Rate this topic

SortedList Class

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

For a list of all members of this type, see SortedList Members.

System.Object
   System.Collections.SortedList

[Visual Basic]
<Serializable>
Public Class SortedList
   Implements IDictionary, ICollection, IEnumerable, ICloneable
[C#]
[Serializable]
public class SortedList : IDictionary, ICollection, IEnumerable,
   ICloneable
[C++]
[Serializable]
public __gc class SortedList : public IDictionary, ICollection,
   IEnumerable, ICloneable
[JScript]
public
   Serializable
class SortedList implements IDictionary, ICollection,
   IEnumerable, ICloneable

Thread Safety

Public static (Shared in Visual Basic) members of this type are safe for multithreaded operations. Instance members are not guaranteed to be thread-safe.

A SortedList 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 could 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.

Remarks

A SortedList is a hybrid between a Hashtable and an Array. When an element is accessed by its key using the Item indexer property, it behaves like a Hashtable. When an element is accessed by its index using GetByIndex or SetByIndex, it behaves like an Array.

A SortedList 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-and-value pair that can be accessed as a DictionaryEntry object. A key cannot be a null reference (Nothing in Visual Basic), but a value can be.

The capacity of a SortedList is the number of elements that the list 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.

The elements of a SortedList 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 removed, the indexing also adjusts accordingly. Therefore, the index of a specific key-and-value pair might change as elements are added or removed from the SortedList.

Operations on a SortedList tend to be slower than operations on a Hashtable 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.

Indexes in this collection are zero-based.

[Visual Basic, C#] 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 is a key-and-value pair, the element type is not the type of the key or the type of the value. Instead, the element type is DictionaryEntry. For example:

[C#] 
foreach (DictionaryEntry myDE in mySortedList) {...}
[Visual Basic] 
Dim myDE As DictionaryEntry
For Each myDE In mySortedList
   ...
Next myDE

[Visual Basic, C#] The foreach statement is a wrapper around the enumerator, which only allows reading from, not writing to, the collection.

Example

[Visual Basic, C#, C++] The following example shows how to create and initialize a SortedList and how to print out its keys and values.

[Visual Basic] 
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("First", "Hello")
        mySL.Add("Second", "World")
        mySL.Add("Third", "!")
        
        ' 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:    !
 

[C#] 
using System;
using System.Collections;
public class SamplesSortedList  {

   public static void Main()  {

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

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

[C++] 
#using <mscorlib.dll>
#using <system.dll>

using namespace System;
using namespace System::Collections;

public __gc class SamplesSortedList  {
public:
    static void PrintKeysAndValues(SortedList __gc *myList) {
        Console::WriteLine(S"\t-KEY-\t-VALUE-");
        for (int i = 0; i < myList->Count; i++) {
            Console::WriteLine(S"\t{0}:\t{1}", myList->GetKey(i), myList->GetByIndex(i));
        }
        Console::WriteLine();
    }
};

int main()  {

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

    // Displays the properties and values of the SortedList.
    Console::WriteLine(S"mySL");
    Console::WriteLine(S"  Count:    {0}", __box(mySL->Count));
    Console::WriteLine(S"  Capacity: {0}", __box(mySL->Capacity));
    Console::WriteLine(S"  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:    !
*/ 

[JScript] No example is available for JScript. To view a Visual Basic, C#, or C++ example, click the Language Filter button Language Filter in the upper-left corner of the page.

Requirements

Namespace: System.Collections

Platforms: Windows 98, Windows NT 4.0, Windows Millennium Edition, Windows 2000, Windows XP Home Edition, Windows XP Professional, Windows Server 2003 family

Assembly: Mscorlib (in Mscorlib.dll)

See Also

SortedList Members | System.Collections Namespace | IComparable | IComparer | IDictionary | Hashtable | Performing Culture-Insensitive String Operations in Collections

Show:
© 2014 Microsoft. All rights reserved.