3.5. Making a Type Sortable
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.Sort
and ArrayList.Sort
methods to allow for a custom sorting of your data types in the
array. In addition, you may need to use this structure in a
SortedList
collection.
Solution
Implement the
IComparable
interface. The following class,
Square
, implements this interface in a way so that
the Array
, ArrayList
, and
SortedList
objects can sort and search an array or
collection of these Square
objects:
public class Square : IComparable { public Square( ){} public Square(int height, int width) { this.height = height; this.width = width; } private int height; private int width; public int Height { get{ return (height); } set{ height = value; } } public int Width { get{ return (width); } set{ width = value; } } public int CompareTo(object obj) { if (this.GetType( ) != obj.GetType( )) { throw (new ArgumentException( "Both objects being compared must be of type Square.")); } else { Square square2 = (Square)obj; long area1 = this.Height * this.Width; long area2 = square2.Height * square2.Width; if (area1 == area2) { return (0); } else if (area1 > area2) { return (1); } else if (area1 < area2) { return (-1); } else { return (-1); } } } public override string ToString( ) { return ("Height:" + height + " Width:" + width); } }
Discussion
By implementing the IComparable
interface on your class (or structure), you can take advantage of the sorting ...
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.