
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
Keeping Your List<T> Sorted
|
305
Discussion
Instead of calling List<T>.Add directly to add elements, use the AddSorted method to
add elements while at the same time keeping the
List<T> sorted. The AddSorted
method accepts a generic type (T) to add to the sorted list.
Likewise, instead of using the
List<T> indexer directly to modify elements, use the
ModifySorted method to modify elements while at the same time keeping the List<T>
sorted. Call this method, passing in the generic type T to replace the existing object
(
item), and the index of the object to modify (index).
The following code exercises the
SortedList<T> class:
class CTest
{
static void Main( )
{
// Create a SortedList and populate it with
// randomly chosen numbers.
SortedList<int> sortedAL = new SortedList<int>( );
sortedAL.AddSorted(200);
sortedAL.AddSorted(20);
sortedAL.AddSorted(2);
sortedAL.AddSorted(7);
sortedAL.AddSorted(10);
sortedAL.AddSorted(0);
sortedAL.AddSorted(100);
sortedAL.AddSorted(-20);
sortedAL.AddSorted(56);
sortedAL.AddSorted(55);
sortedAL.AddSorted(57);
sortedAL.AddSorted(200);
sortedAL.AddSorted(-2);
sortedAL.AddSorted(-20);
sortedAL.AddSorted(55);
sortedAL.AddSorted(55);
// Display it.
foreach (int i in sortedAL)
{
Console.WriteLine(i);
}
// Now modify a value at a particular index.
sortedAL.ModifySorted(0, ...