Use a Sorted List

Problem

You want to use a collection that is automatically sorted every time an item is added or removed.

Solution

Use the System.Collections.SortedList type, which sorts items based on the key.

Discussion

The SortedList class is a key-based dictionary collection that stores items in a perpetually ordered state. That makes it slower when adding or removing items. However, using a SortedList collection is usually faster than continuously resorting an Array or ArrayList. Behind the scenes, a sorted list uses two arrays: one to store key values, and one to store the data itself (or the object reference).

The most important aspect to understand about the SortedList class is that it orders items based on the key value, not the object itself. ...

Get Microsoft® Visual Basic® .NET Programmer's Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.