SortedList Class Home
This page is specific to:.NET Framework Version:1.12.03.03.54.0
.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.

Namespace:  System.Collections
Assembly:  mscorlib (in mscorlib.dll)
Syntax

'Usage

Dim instance As SortedList

'Declaration

<SerializableAttribute> _
<ComVisibleAttribute(True)> _
Public Class SortedList _
    Implements IDictionary, ICollection, IEnumerable, ICloneable
Remarks

For the generic version of this collection, see System.Collections.Generic..::.SortedList<(Of <(TKey, 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 nullNothingnullptra null reference (Nothing in Visual Basic), 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.

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

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



Inheritance Hierarchy

System..::.Object
  System.Collections..::.SortedList
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.

Platforms

Windows 7, Windows Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP Starter Edition, Windows Server 2008 R2, Windows Server 2008, Windows Server 2003, Windows Server 2000 SP4, Windows Millennium Edition, Windows 98, Windows CE, Windows Mobile for Smartphone, Windows Mobile for Pocket PC, Xbox 360, Zune

The .NET Framework and .NET Compact Framework do not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.
Version Information

.NET Framework

Supported in: 3.5, 3.0, 2.0, 1.1, 1.0

.NET Compact Framework

Supported in: 3.5, 2.0

XNA Framework

Supported in: 3.0, 2.0, 1.0
See Also

Reference

Other Resources

Community Content

SortedListSample Using PowerShell
Added by:Thomas Lee
# get-sortedlist.ps1
# Sortedlist sample using PowerShell
# Thomas Lee - tfl@psp.co.uk
 
# Define helper function
function PrintKeysAndValues( $myList )  {
"`t-KEY-`t-VALUE-"
for ( [int] $i = 0; $i -lt $myList.Count; $i++ ) {
"`t{0}:`t{1}" -F $myList.GetKey($i), $myList.GetByIndex($i)
}
""
}
 
# Create and initialise a new SortedList object
$mySL = new-object system.collections.SortedList
$mySL.Add("First", "Hello")
$mySL.Add("Second", "World")
$mySL.Add("Third", "!")
 
# Display the properties and values of the SortedList
"`$mySL"
" Count: {0}" -f $mySL.Count
" Capacity: {0}" -f $mySL.Capacity
" Keys and Values:"
PrintKeysAndValues( $mySL )
 
# Add two more and display results
$mysl.add("aaaa", "aaaa")
$mysl.add("zzzz" , "zzzz")
 
# display results
"`$mySL after two additions"
" Count: {0}" -f $mySL.Count
" Capacity: {0}" -f $mySL.Capacity
" Keys and Values:"
PrintKeysAndValues( $mySL )

This script produces the following output

PS D:\foo> 
D:\foo\get-sortedlist.ps1
$mySL
Count: 3
Capacity: 16
Keys and Values:
-KEY- -VALUE-
First: Hello
Second: World
Third: !
 
$mySL after two additions
Count: 5
Capacity: 16
Keys and Values:
-KEY- -VALUE-
aaaa: aaaa
First: Hello
Second: World
Third: !
zzzz: zzzz
  

Sample Data Shouldn't Already be Sorted
Added by:dbottjer

The example already has the sample data entered in alphabetical order as shown below:

SortedList mySL = new SortedList();
mySL.Add("First", "Hello");
mySL.Add("Second", "World");
mySL.Add("Third", "!");

It would be less confusing and a better demonstration to change the order.

Simple getEnumerator from SortedList
Added by:Allan Pedroni

This example has some data and get enumerator from their values,keys shown below.

SortedList sl = new SortedList();

sl.Add("hip", "hop");
sl.Add("fest", "country");
sl.Add("quer", "bolete");

if ( x.Contains("hip") )
Console.Write("Hip has gone!");


IDictionaryEnumerator iDic = x.GetEnumerator();


while ( iDic.MoveNext() )
Console.Write("key:" + iDic.Key.ToString() + " value:" + iDic.Value.ToString());

Must Keys Be Unique?
Added by:OxG
Doesn't say, would be helpful if it did...
Regarding Key Uniqueness
Added by:Thomas Lee

To answer OxG's question above, the answer is that keys in a sorted list must be unique. Thus trying to call the Add() method with a non-unique key will generate an exception, as shown in the following PowerShell session log:

PSH [C:\foo]: $sl = New-Object system.Collections.SortedList
PSH [C:\foo]: $sl
PSH [C:\foo]: $sl.Add("first","foo")
PSH [C:\foo]: $sl
Name                           Value
---- -----
first foo
  
PSH [C:\foo]: $sl.Add("first","foo2")
Exception calling "Add" with "2" argument(s): "Item has already been added. Key in dictionary: 'first' Key being added: 'first'"
At line:1 char:8
+ $sl.Add <<<< ("first","foo2")
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : DotNetMethodException
RE: Must keys be unique
Added by:Phil Preen
Actually it does say "a SortedList does not allow duplicate keys".
Any suggestions for a class that does allow duplicates?
SortList not sorted
Added by:Fabio Milheiro
I think many people are looking for a class key/value pair that maintains the order in which the elements are inserted.

Can anyone leads us there?

Thank you!
© 2009 Microsoft Corporation. All rights reserved.   Terms of Use | Trademarks | Privacy Statement
Page view tracker
Rate the Lightweight library
x
Lightweight builds on ScriptFree (loband) by adding features you've requested: a SearchBox and default code language selection.
Do you like the SearchBox?
Do you like the tabbed code blocks?
How useful is this topic?
Tell us more.
Thanks
x
You're helping to improve MSDN Online.
Feedback
Switch View
Classic
Lightweight Beta
ScriptFree
Switch View