
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
308
|
Chapter 5: Collections
// Display sorted list.
foreach (string obj in values)
Console.WriteLine("Value: " + obj);
// Reverse the sorted value list.
Console.WriteLine( );
values.Reverse( );
// Display sorted list.
foreach (string obj in values)
Console.WriteLine("Value: " + obj);}
The key/value pairs are displayed as shown:
Key: 1 Value: one
Key: 2 Value: two
Key: 3 Value: three
Key: 4 Value: four
Key: 5 Value: five
Key: 5 Value: five
Key: 4 Value: four
Key: 3 Value: three
Key: 2 Value: two
Key: 1 Value: one
Value: five ← Notice that the values are sorted alphabetically
Value: four
Value: one
Value: three
Value: two
Value: two
Value: three
Value: one
Value: four
Value: five
Discussion
The Dictionary<T,U> object exposes two useful properties for obtaining a collection
of its keys or values. The
Keys property returns an ICollection containing all the keys
currently in the
Dictionary<T,U>. The Values property returns the same for all values
currently contained in the
Dictionary<T,U>.
The
GetKeys method uses the Keys property. Once the ICollection of keys is returned
through this property, a new
List<T> is created to hold the keys. This List<T> is then
returned to the caller. The
GetValues method works in a similar manner except that
it uses the
Values property.