
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
296
|
Chapter 5: Collections
Discussion
The CountAll method accepts a search value (searchValue) of type object. This
method then proceeds to count the number of times the search value appears in the
ListEx<T> class. This method may be used when the ListEx<T> is sorted or unsorted.
If the
ListEx<T> is sorted (a ListEx<T> is sorted by calling the Sort method), the
BinarySearchCountAll method can be used to increase the efficiency of the searching.
This is done by making use of the
BinarySearch method on the ListEx<T> class,
which is much faster than iterating through the entire
ListEx<T>x. This is especially
true as the
ListEx<T> grows in size.
The following code exercises these two new methods of the
ListEx<T> class:
class Test
{
static void Main( )
{
ListEx<int> arrayExt = new ListEx<int>( );
arrayExt.Add(-2);
arrayExt.Add(-2);
arrayExt.Add(-1);
arrayExt.Add(-1);
arrayExt.Add(1);
arrayExt.Add(2);
}
}
return (foundCounter);
}
// Count the number of times an item appears in this sorted List<T>.
public int BinarySearchCountAll(T searchValue)
{
// Search for first item.
int center = this.BinarySearch(searchValue);
int left = center;
while (left > 0 && this[left-1].Equals(searchValue))
{
left -= 1;
}
int right = center;
while (right < (this.Count – 1) && this[right+1].Equals(searchValue))