Sorted Lists C# Help

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 books 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 book 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. Ua key already exists, the Add () method thrQws an exception of type .».rgumentException.Uthe same key is used with the indexer, the new value replaces the old value.

SortedList<string, string> books =
new.SortedList<string, string>();
books.Add(“.NET 2.0 Wrox Box”,
“Professional CI 2005 with .NET 3.0”,
books [“Beginning Visual CI 2005”)
books[“Professional CI 2008”) =

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, and the value can be accessed with the Value property.

foreach (KeyValuePair<string, string> book in
Console.WriteLine(” (O), (1)”, book. Key,
book. Value) ;

The iteration displays book titles and ISBN numbers ordered by the key:

.NET 2.0 Wrox Box, 978-0-470-04840-5
Beginning Visual C. 2005, 978-0-7645-4382-1
Professional C# 2005 with .NET 3.0, 978-0-470-12472-7
Professional C. 2008, 978-0-470-19137-6

You can also access the values and keys by using the Values and Keys properties. The Values property returns IList<TValue> and the Keys property returns IList<TKey>, so you can use these properties
with a f or each:

foreach (string isbn in books. Values)
foreach (string title in books.Keys)


The first loop displays the values, and next the keys:

.~IET 2.0 Wrox Box
Beginning Visual CI 2005
Professional C# 2005 with .NET 3.0
Professional C# 2008

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.

In addition to the generic SortedList<TKey. TValue>. a corresponding non-generic list Termed SortedList is available.

Posted on October 29, 2015 in Collections

Share the Story

Back to Top
Share This