O'Reilly logo

C# Cookbook by Jay Hilyard, Stephen Teilhet

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required