Skip to Main Content
C# Cookbook, 2nd Edition
book

C# Cookbook, 2nd Edition

by Jay Hilyard, Stephen Teilhet
January 2006
Intermediate to advanced content levelIntermediate to advanced
1184 pages
43h 23m
English
O'Reilly Media, Inc.
Content preview from C# Cookbook, 2nd Edition
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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

C# Cookbook

C# Cookbook

Joe Mayo
C# Cookbook

C# Cookbook

Stephen Teilhet, Jay Hilyard
Head First C#, 4th Edition

Head First C#, 4th Edition

Andrew Stellman, Jennifer Greene

Publisher Resources

ISBN: 0596100639Supplemental ContentCatalog PageErrata