typestar

Sorted collections in C#

Collections that keep themselves in order.

var ranking = new SortedDictionary<int, string>
{
    [3] = "bronze", [1] = "gold", [2] = "silver",
};
// a sorted dictionary iterates in key order, however keys arrived
foreach (var (place, medal) in ranking)
{
    Console.WriteLine($"{place}: {medal}");
}

var tags = new SortedSet<string> { "web", "api", "cli", "api" };
Console.WriteLine(string.Join(",", tags));
Console.WriteLine(tags.Min + " .. " + tags.Max);

How it works

  1. A SortedDictionary iterates by key however keys arrived.
  2. A SortedSet deduplicates and sorts in one structure.
  3. Min and Max are free once the tree keeps order.

Keywords and builtins used here

The run, in numbers

Lines
13
Characters to type
407
Tokens
97
Three-star pace
90 tpm

At the three-star pace of 90 tokens a minute, this run takes about 65 seconds.

Type this snippet

Step 3 of 3 in More collections, step 12 of 17 in The .NET library.

← Previous Next →