
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
306
|
Chapter 5: Collections
// Display it.
Console.WriteLine( );
foreach (int i in sortedAL)
{
Console.WriteLine(i);
}
}
}
This method automatically places the new item in the List<T> while keeping its sort
order; this is done without having to explicitly call
List<T>.Sort. The reason this
works is because the AddSorted method first calls the BinarySearch method and
passes it the object to be added to the
ArrayList. The BinarySearch method will
either return the index where it found an identical item or a negative number that
you can use to determine where the item that you are looking for should be located.
If the
BinarySearch method returns a positive number, you can use the List<T>.
Insert
method to insert the new element at that location, keeping the sort order
within the
List<T>. If the BinarySearch method returns a negative number, you can
use the bitwise complement operator
~ to determine where the item should have
been located, had it existed in the sorted list. Using this number, you can use the
List<T>.Insert method to add the item to the correct location in the sorted list while
keeping the correct sort order.
You can remove an element from the sorted list without disturbing the sort order,
but modifying an element’s value in the
List<T> most likely will cause the sorted list
to