Skip to main content
Version: 1.6.0

SortedList

The SortedList<TKey, TValue>, and SortedList are collection classes that can store key-value pairs that are sorted by the keys based on the associated IComparer implementation. For example, if the keys are of primitive types, then sorted in ascending order of keys.

Tuval Framework supports generic type of this class in Typescript. You can use non-generic version of SortedList in javascript.

SortedList Characteristics

  • SortedList<TKey, TValue> is an array of key-value pairs sorted by keys.
  • Sorts elements as soon as they are added. Sorts primitive type keys in ascending order and object keys based on IComparer.
  • A key must be unique and cannot be null or underined.
  • A value can be null, undeined or duplicate.
  • A value can be accessed by passing associated key in the indexer Get and Set methods. mySortedList.Get(key) or mySortedList.Set(key, value)
  • Contains elements of type KeyValuePair<TKey, TValue>
  • It uses less memory than SortedDictionary<TKey,TValue>.
  • It is faster in the retrieval of data once sorted, whereas SortedDictionary<TKey, TValue> is faster in insertion and removing key-value pairs.

Creating a SortedList

The following example demonstrates how to create a generic SortedList<TKey, TValue>, and add key-value pairs in it.

import { SortedList, int} from '@tuval/core'

//SortedList of int keys, string values
const numberNames:SortedList<int, string> = new SortedList<int, string>();
numberNames.Add(3, "Three");
numberNames.Add(1, "One");
numberNames.Add(2, "Two");
numberNames.Add(4, null);
numberNames.Add(10, "Ten");
numberNames.Add(5, "Five");
numberNames.Add(8, undefined);

//The following will throw exceptions
//numberNames.Add("Three", 3); //Compile-time error in Typescript: key must be int type
//numberNames.Add(1, "One"); //Run-time exception: duplicate key
//numberNames.Add(null, "Five");//Run-time exception: key cannot be null

In the above example, a generic SortedList<TKey, TValue> object is created by specifying the type of keys and values it is going to store. The SortedList<int, string> will store keys of int type and values of string type.

The Add() method is used to add a single key-value pair in a SortedList. Keys cannot be null, undefined or duplicate. If found, it will throw a run-time exception. Values can be duplicate , null or undefined.

Use the collection-initializer syntax to initialize a SortedList with multiple key-value pairs at the time of instantiating, as shown below.

import { SortedList, int} from '@tuval/core'

//Creating a SortedList of string keys, string values
//using collection-initializer syntax
const cities:SortedList<string,string> = new SortedList<string,string>([
["London", "UK"],
["New York", "USA"],
["İstanbul", "Turkey"],
["Johannesburg", "South Africa"]
]);

The SortedList rearranges key-value pairs in the ascending order of keys as soon as a key-value pair added. The following example displays all the keys and values using foreach loop.

import { SortedList, int, Console, foreach } from '@tuval/core'

const numberNames: SortedList<int,string> = new SortedList<int,string>([
[ 3, "Three"],
[ 5, "Five"],
[ 1, "One"]
]);

Console.WriteLine("---Initial key-values--");

foreach( numberNames, ( kvp)=>{
Console.WriteLine("key: {0}, value: {1}", kvp.Key , kvp.Value );
});


numberNames.Add(6, "Six");
numberNames.Add(2, "Two");
numberNames.Add(4, "Four");

Console.WriteLine("---After adding new key-values--");

foreach(numberNames, (kvp)=>{
Console.WriteLine("key: {0}, value: {1}", kvp.Key , kvp.Value );
});

Accessing SortedList

Specify a key in the indexer method sortedList.Get(key), to get or sortedList.Set(key, value) method for set a value in the SortedList.

const numberNames:SortedList<int,string> = new SortedList<int,string>(
[
[3, "Three"],
[1, "One"],
[2, "Two"]
]);

Console.WriteLine(numberNames.Get(1)); //output: One
Console.WriteLine(numberNames.Get(2)); //output: Two
Console.WriteLine(numberNames.Get(3)); //output: Three
//Console.WriteLine(numberNames[10]); //run-time KeyNotFoundException

numberNames.Set(2, "TWO"); //updates value
numberNames.Set(4, "Four"); //adds a new key-value if a key does not exists

Above, numberNames.Get(10) will throw a KeyNotFoundException because specified key 10 does not exist in a sortedlist. To prevent this exception, use ContainsKey() or TryGetValue() methods, as shown below.

const numberNames:SortedList<int, string> = new SortedList<int,string>([
[3, "Three"],
[1, "One"],
[2, "Two"]
]);
if(numberNames.ContainsKey(4)){
numberNames[4] = "four";
}

int result;
if(numberNames.TryGetValue(4, out result))
Console.WriteLine("Key: {0}, Value: {1}", 4, result);

Use Keys and Values properties if you want to iterate a SortedList using a for loop.

const numberNames:SortedList<int, string> = new SortedList<int,string>( [
[ 3, "Three" ],
[ 1, "One" ],
[ 2, "Two" ]
]);
for (int i = 0; i < numberNames.Count; i++) {
Console.WriteLine("key: {0}, value: {1}", numberNames.Keys[i], numberNames.Values[i]);
}

Remove Elements from SortedList

Use the Remove(key) and RemoveAt(index) methods to remove key-value pairs from a SortedList.

const numberNames:SortedList<int,string> = new SortedList<int,string>(
[
[3, "Three"],
[1, "One"],
[2, "Two"],
[5, "Five"],
[4, "Four"]
]);

numberNames.Remove(1);//removes key 1 pair
numberNames.Remove(10);//removes key 1 pair, no error if not exists

numberNames.RemoveAt(0);//removes key-value pair from index 0
//numberNames.RemoveAt(10);//run-time exception: ArgumentOutOfRangeException

foreach(numberNames, (kvp)=>{
Console.WriteLine("key: {0}, value: {1}", kvp.Key , kvp.Value );
});