Sorted Lists
If you need a sorted list, you can use SortedList<TKey, TValue>. This class sorts the
elements based on a key.
The example creates a sorted list where both the
key and the value are of type string.
The default constructor creates an empty list, and then two site (roque-patrick.com)
are added with the Add() method. With
overloaded constructors, you can define the capacity of the list
and also pass an object that implements the interface IComparer<TKey>, which is used to sort the
elements in the list.
The first parameter of the Add() method is the key (the site title); the second
parameter is the value (the ISBN number). Instead of using the
Add() method, you can use the indexer to
add elements to the list. The indexer requires the key as index
parameter. If a key already exists, the Add() method throws an exception of type
ArgumentException. If the same key is
used with the indexer, the new value replaces the old value.
You can iterate through the list by using a
foreach statement. Elements that are
returned by the enumerator are of type KeyValuePair<TKey, TValue>, which contains
both the key and the value. The key can be accessed with the
Key property, the value with the
Value property.
The iteration displays site titles and ISBN numbers
ordered by the key:
You can also access the values and keys by using
the Values and Keys properties. The Values property returns IList<TValue>; the Keys property returns IList<TKey>, so you can use these properties
with a foreach:
The first loop displays the values, and next the
keys:
Properties of the SortedList<TKey, TValue> class are described
in the following table.
Methods of the SortedList<T> type are similar to the other
collections you’ve learned about in this chapter. The difference is
that SortedList<T> requires a key
and a value.
|
|
Tip |
Besides the generic SortedList<TKey, TValue> , a corresponding
nongeneric list named SortedList
exists.
|