It is possible use the SortedList in the same way as a Dictionary. In programs, the SortedList may require less memory for storage.
using System;
using System.Collections.Generic;
// Create SortedList with 3 keys and values.
var sorted = new SortedList<string, int>();
sorted.Add(
"zebra", 3);
sorted.Add(
"cat", 1);
sorted.Add(
"dog", 2);
// Use ContainsKey.
bool contains1 = sorted.ContainsKey(
"?");
Console.WriteLine(
"contains ? = " + contains1);
// Use TryGetValue.
int value;
if (sorted.TryGetValue(
"zebra", out value))
{
Console.WriteLine(
"zebra = " + value);
}
// Use item indexer.
Console.WriteLine(
"cat = " + sorted[
"cat"]);
// 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(
"cat");
Console.WriteLine(
"index of cat = " + index1);
int index2 = sorted.IndexOfValue(3);
Console.WriteLine(
"index of 3 (value) = " + index2);
// Display Count.
Console.WriteLine(
"count = " + sorted.Count);
contains ? = False
zebra = 3
cat = 1
[cat, 1]
[dog, 2]
[zebra, 3]
index of cat = 0
index of 3 (value) = 2
count = 3