
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
Retrieving All Instances of a Specific Item in a List<T>
|
299
Discussion
The GetAll and BinarySearchGetAll methods used in this recipe are very similar to
those used in Recipe 5.6. The main difference is that these methods return the actual
items found in an
object array instead of a count of the number of times an item was
found. The main thing to keep in mind when choosing a method is whether you are
going to be searching a
List<T> that is sorted. Choose the GetAll method to obtain an
array of all found items from an unsorted
List<T>, and choose the BinarySearchGetAll
method to get all items in a sorted List<T>.
The following code exercises these two new methods of the
ListEx<T> class:
class Test
{
}
}
return (foundItem.ToArray( ));
}
// The method to retrieve all matching objects in a sorted ListEx<T>
public T[] BinarySearchGetAll(T searchValue)
{
bool done = false;
List<T> RetObjs = new List<T>( );
// Search for first item.
int center = this.BinarySearch(searchValue);
if (center > 0)
{
RetObjs.Add(this[center]);
int left = center;
while (left > 0 && this[left - 1].Equals(searchValue))
{
left -= 1;
RetObjs.Add(this[left]);
}
int right = center;
while (right < (this.Count - 1) &&
this[right + 1].Equals(searchValue))
{
right += 1;
RetObjs.Add(this[right]);
}
}
return (RetObjs.ToArray( ...