3.3. Making a Type Searchable

Problem

You have a data type that will be stored as elements in a List<T>. You would like to use the BinarySearch method to allow for custom searching of your data types in the list.

Solution

Use the IComparable<T> and IComparer<T> interfaces. The Square class, from Recipe 3.1, implements the IComparable<T> interface in such a way that the List<T> and SortedList<K,V> collections can sort and search an array or collection of Square objects.

Discussion

By implementing the IComparable<T> interface on your class (or structure), you can take advantage of the search routines of the List<T> and SortedList<K,V> 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<T>. CompareTo method.

To implement the CompareTo method, see Recipe 3.2.

The List<T> class provides a BinarySearch method to perform a search on the elements in that list. 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 ContainsKey method, which performs a binary search on the key contained in the list. The ContainsValue method of the SortedList class performs 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. The Compare and CompareTo methods do not have any effect ...

Get C# 3.0 Cookbook, 3rd Edition 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.