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 these in a way so 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
, and
SortedList
classes. The algorithms for searching
are built into these classes; all you have to do is tell them how to
search through your classes via the code you implement in the
IComparable.CompareTo
method.
To implement the CompareTo
method, see Recipe 3.5.
The Array
and ArrayList
classes
provide a BinarySearch
method to perform 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 Contains
, ContainsKey
, and
ContainsValue
methods to perform a linear search
when searching for values. This linear search uses the
Equals
method of the elements in the
SortedList
collection to do its work (to overload
the Equals
method, see Recipe 3.9), the Compare
and
CompareTo
methods do not ...
Get C# Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.