C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Types: The SortedList instance has 2 type parameters (string and int) that describe the requirements for elements.
Generic Class, MethodInfo: You will get a compile-time error if you try to use a wrongly-typed parameter.
Tip: ContainsKey and TryGetValue test the internal data structure (an array) in the SortedList instance.
TryGetValue: This can obtain the value associated with the key if it is found in the data structure. It can boost performance on lookups.
C# program that uses SortedList
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
//
// Create SortedList with 3 keys and values.
//
SortedList<string, int> sorted = new SortedList<string, int>();
sorted.Add("Codex", 3);
sorted.Add("dot", 1);
sorted.Add("net", 2);
//
// Test SortedList with ContainsKey method.
//
bool contains1 = sorted.ContainsKey("java");
Console.WriteLine("contains java = " + contains1);
//
// Use TryGetValue method.
//
int value;
if (sorted.TryGetValue("Codex", out value))
{
Console.WriteLine("Codex key is = " + value);
}
//
// Use item indexer.
//
Console.WriteLine("dot key is = " + sorted["dot"]);
//
// Loop over SortedList data.
//
foreach (var pair in sorted)
{
Console.WriteLine(pair);
}
//
// Get index of key and then index of value.
//
int index1 = sorted.IndexOfKey("net");
Console.WriteLine("index of net (key) = " + index1);
int index2 = sorted.IndexOfValue(3);
Console.WriteLine("index of 3 (value) = " + index2);
//
// Display Count property.
//
Console.WriteLine("count is = " + sorted.Count);
}
}
Output
contains java = False
Codex key is = 3
dot key is = 1
[dot, 1]
[net, 2]
[Codex, 3]
index of net (key) = 1
index of 3 (value) = 2
count is = 3
IndexOfKey: You can see the IndexOfKey method is invoked each time. The internal array is accessed at that index.
IndexerLookup implementation for SortedList: C#
public TValue this[TKey key]
{
get
{
int index = this.IndexOfKey(key);
if (index >= 0)
{
return this.values[index];
}
ThrowHelper.ThrowKeyNotFoundException();
return default(TValue);
}
}
public int IndexOfKey(TKey key)
{
if (key == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
}
int num = Array.BinarySearch<TKey>(this.keys, 0, this._size,
key, this.comparer);
if (num < 0)
{
return -1;
}
return num;
}
And: For this reason, the SortedList will be slower than a Dictionary in many programs.
Info: For large collections and collections where the size is indeterminate at compile-time and may be large, consider a Dictionary.
DictionaryFurther: The HybridDictionary and SortedList collections perform well on small data sets.
HybridDictionaryNote: These allocations will only copy the element references. They won't copy all the strings if you use that type as the key or value.