Skip to content

Instantly share code, notes, and snippets.

@jianminchen
Created October 25, 2017 18:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jianminchen/76bf8046d5fd4e327555197bcf9dc6b3 to your computer and use it in GitHub Desktop.
Save jianminchen/76bf8046d5fd4e327555197bcf9dc6b3 to your computer and use it in GitHub Desktop.
Csharp 2000 things - Item 135: #135 – Implementing IComparable to Allow Sorting a Custom Type
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
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment