C# SortedList Collection Tutorial

In this tutorial we learn about a non-generic single type data collection called the SortedList.

We cover how to declare and initialize a sortedlist as well as how to add and access values.

What is a SortedList

A SortedList is a combination of an Array and a Hashtable and represents a collection of key/value pairs that are sorted by keys.

SortedList has generic and non-generic variations. In this lesson we’ll learn about non-generic sorted lists.

The SortedList namespace

SortedList, as a non-generic collection class, is defined in the System.Collections namespace. Before we can use a SortedList, we must specify this namespace at the top of the document.

Example:
using System;
using System.Collections;

How to declare a SortedList

A SortedList is declared with the new keyword. The new keyword will create a new instance of the SortedList class and store it in the list_name object.

Syntax:
SortedList list_name = new SortedList();
Example:
using System.Collections;

namespace SortedLists
{
    class Program
    {
        static void Main()
        {
            SortedList sl = new SortedList();
        }
    }
}

In the example above, we declare a new SortedList and store it in an object called sl.

How to initialize a SortedList with values

If we know the values we want to store in a SortedList, we can directly assign those values to the SortedList when its declared.

We initialize a SortedList with initialization syntax. In the code block of the new SortedList declaration, we specify keys and values separated by a comma between a set of curly braces. Each key/value set is also separated by a comma.

Syntax:
SortedList list_name = new SortedList()
{
    { key, value },
    { key, value }
};
Example:
using System.Collections;

namespace SortedLists
{
    class Program
    {
        static void Main()
        {
            SortedList sl = new SortedList()
            {
                { 1, "One" },
                { 2, "Two" }
            };
        }
    }
}

A SortedList can be of any single data type, but it cannot contain mixed data types in the same list.

For example, if we initialize a SortedList with string values, it can only contain string values.

Example:
using System;
using System.Collections;

namespace SortedLists
{
    class Program
    {
        static void Main()
        {
            SortedList sl = new SortedList()
            {
                { 1, "One" },
                { "Two", 2 } // Will cause runtime exception
            };
        }
    }
}

In the example above, we try to store an int value where the sorted list expects a string. This causes a runtime exception.

Output:
System.InvalidOperationException: 'Failed to compare two elements in the array.'

How to assign single values to a SortedList with the indexer

To add a value to the SortedList with the indexer, we use square brackets after the list name, followed by the assignment operator and the value to add.

We must specify the key between the square brackets that will correspond to the value.

Syntax:
list_name[key] = value;
Example:
using System.Collections;

namespace SortedLists
{
    class Program
    {
        static void Main()
        {
            SortedList sl = new SortedList();

            sl[1] = "One";
            sl[2] = "Two";
        }
    }
}

In the example above, we assign the value “One” to the key 1, and the value “Two” to the key 2. When accessing the values in the future, we will use those keys to get the corresponding values.

How to assign values to a SortedList with Add()

The Add() function is an alternative to the indexer and allows us to add a value to the SortedList.

We write the list name, followed by a dot and the Add() function. The Add() function takes the key and value, separated by a comma, as arguments.

Syntax:
list_name.Add(key, value);
Example:
using System.Collections;

namespace SortedLists
{
    class Program
    {
        static void Main()
        {
            SortedList sl = new SortedList();

            sl.Add(1, "One");
            sl.Add(2, "Two");
        }
    }
}

In the example above, we use the alternative method to add values to a SortedList, the Add() function.

How to access a single value in a SortedList with the indexer

We can access a single value in a SortedList with the indexer. We write the list name, followed by square brackets and the key of the value we want to access.

Syntax:
list_name[key]
Example:
using System;
using System.Collections;

namespace SortedLists
{
    class Program
    {
        static void Main()
        {
            SortedList sl = new SortedList();

            sl.Add(1, "One");

            Console.WriteLine(sl[1]);
            Console.ReadLine();
        }
    }
}

In the example above, we create a new SortedList instance, then add a value with a key of 1. In the WriteLine() function we access the value with the key 1.

How to access multiple values in a SortedList with a loop

To access multiple values in a SortedList we can use a loop. In this case we use a foreach loop.

Example:
using System;
using System.Collections;

namespace SortedLists
{
    class Program
    {
        static void Main()
        {
            SortedList sl = new SortedList()
            {
                { 1, "One" },
                { 2, "Two" },
                { 3, "Three" },
                { 4, "Four" },
                { 5, "Five" },
            };

            foreach(DictionaryEntry entry in sl)
            {
                Console.WriteLine("Key: {0} | Value: {1}", entry.Key, entry.Value);
            }

            Console.ReadLine();
        }
    }
}

In the example above, we use DictionaryEntry as a type for the temporary foreach variable. DictionaryEntry is a struct that defines a dictionary key/value pair.

This allows us to use entry.Key and entry.Value to access the key/value pairs.

A list of common properties of the SortedList class

The following table lists some of the commonly used properties of the SortedList class:

PropertyDescription
CountGets the number of elements contained in a SortedList
CapacityGets or sets the capacity of a SortedList
ItemGets or sets the element at the specified key in a SortedList
KeysGet a list of keys in a SortedList
ValuesGet a list of values in a SortedList

A list of common methods of the SortedList class

The following table lists some of the commonly used methods of the SortedList class:

MethodDescription
Add(key, value)Adds an element with the specified key and value into a SortedList
Remove(key)Removes the element with the specified key from a SortedList
RemoveAt(index)Removes the element at the specified index from a SortedList
ContainsKey(key)Checks whether a SortedList contains a specific key
ContainsValue(value)Checks whether a SortedList contains a specific value
GetByIndex(index)Gets the value at the specified index of a SortedList
GetKey(index)Gets the key at the specified index of a SortedList
IndexOfKey(key)Returns the index of the specified key in a SortedList
IndexOfValue(value)Returns the index of the first occurrence of the specified value in a SortedList
TrimToSize()Sets the capacity to the actual number of elements in the SortedList
Clear()Remove all elements from a SortedList

Summary: Points to remember

  • A non-generic SortedList is a collection of key/value pairs that are sorted by keys.
  • A SortedList may be of any type, but it can only contain values of a single type.
  • A SortedList can be initialized if we know the values we want to store beforehand.
  • We can add single values with the indexer or with the Add() function. In both of these, we must specify a key to correspond with the given value.