Introduction
One apple a day, keep doctor away. One program a day, also keep programmer awake. Today a small program keeps me awake to look into a few things, IComparer vs IComparable, throw new ArgumentExcecption on line 44.
I like to share my practice using C# 2000 things, item 135: Implement IComparable to allow sorting a custom type.
Here is the C# code.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Text; | |
using System.Threading.Tasks; | |
namespace ArraySort_Example | |
{ | |
/// <summary> | |
/// Oct. 25, 2017 | |
/// Julia learns C# 2000 things | |
/// #135 – Implementing IComparable to Allow Sorting a Custom Type | |
/// https://csharp.2000things.com/2010/10/30/135-implementing-icomparable-to-allow-sorting-a-custom-type/ | |
/// Arrays of elements that belong to a custom type cannot be sorted, unless the type implements | |
/// the IComparable interface. | |
/// | |
/// To make elements of a custom type sortable, you need to implement IComparable in your type. | |
/// IComparable consists of the single method CompareTo, which compares two objects. | |
/// | |
/// Here’s an example of a Person class implementing CompareTo to sort people in LastName/FirstName order: | |
/// </summary> | |
class Person : IComparable | |
{ | |
public string FirstName { get; set; } | |
public string LastName { get; set; } | |
public Person(string firstName, string lastName) | |
{ | |
FirstName = firstName; | |
LastName = lastName; | |
} | |
/// <summary> | |
/// CompareTo | |
/// </summary> | |
/// <param name="obj"></param> | |
/// <returns></returns> | |
public int CompareTo(object obj) | |
{ | |
Person other = obj as Person; | |
if (other == null) | |
{ | |
throw new ArgumentException("Object is not a Person"); | |
} | |
else | |
{ | |
// Sort by LastName, then by FirstName (ignore case) | |
int compare = this.LastName.ToLower().CompareTo(other.LastName.ToLower()); | |
if (compare == 0) | |
{ | |
compare = this.FirstName.ToLower().CompareTo(other.FirstName.ToLower()); | |
} | |
return compare; | |
} | |
} | |
} | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
Person[] folks = new Person[4]; | |
folks[0] = new Person("Bronte", "Emily"); | |
folks[1] = new Person("Bronte", "Charlotte"); | |
folks[2] = new Person("Tennyson", "Alfred"); | |
folks[3] = new Person("Mailer", "Norman"); | |
Array.Sort(folks); // C. Bronte, E. Bronte, Mailer, Tennyson | |
} | |
} | |
} |
No comments:
Post a Comment