3.2. Making a Type Sortable
Problem
You have a data type that will be stored as elements in a List<T>
or a SortedList<K,V>
. You would like to use the List<T>
.Sort method or the internal sorting mechanism of SortedList<K,V>
to allow custom sorting of your data types in the array. In addition, you may need to use this type in a SortedList
collection.
Solution
Example 3-1 demonstrates how to implement the IComparable<T>
interface. The Square
class shown in Example 3-1 implements this interface in such a way that the List<T>
and SortedList<K,V>
collections can sort and search for these Square
objects.
Example 3-1. Making a type sortable by implementing IComparable<T>
public class Square : IComparable<Square>
{ public Square( ){} public Square(int height, int width) { this.Height = height; this.Width = width; } public int Height { get; set; } public int Width { get; set; } public int CompareTo(object obj) { Square square = obj as Square; if (square != null) return CompareTo(square); throw new ArgumentException("Both objects being compared must be of type Square."); } public override string ToString( ) { return ("Height:" + this.Height + " Width:" + this.Width); } public override bool Equals(object obj) { if (obj == null) return false; Square square = obj as Square; if(square != null) return this.Height == square.Height; return false; } public override int GetHashCode( ) { return this.Height.GetHashCode( ) | this.Width.GetHashCode( ); } public static bool operator ==(Square x, Square y) { ...
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.