
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
112
|
Chapter 3: Classes and Structures
3.6 Making a Type Searchable
Problem
You have a data type that will be stored as elements in an array or an ArrayList. You
would like to use the
Array.BinarySearch and ArrayList.BinarySearch methods to
allow for custom searching of your data types in the array.
Solution
Use the IComparable and IComparer interfaces. The Square class, from Recipe 3.5,
implements the IComparable interface in such a way that the Array, ArrayList, and
SortedList objects can sort and search an array or collection of Square objects.
Discussion
By implementing the IComparable interface on your class (or structure), you can take
advantage of the search routines of the
Array, ArrayList, List<T>, and SortedList
classes. The algorithms for searching are built into these classes; all you have to do is
tell them how to search your classes via the code you implement in the
IComparable.
CompareTo
method.
To implement the
CompareTo method, see Recipe 3.5.
The
Array, ArrayList, and List<T> classes provide a BinarySearch method to per-
form a search on the elements in that array. The elements are compared against an
object passed to the
BinarySearch method in the object parameter. The SortedList
class does not have a BinarySearch method; instead, it has the Contains and
ContainsKey methods, which ...