Created
October 25, 2017 20:56
Star
You must be signed in to star a gist
C sharp 2000 things - Item 137 - – Sorting an Array Using an Independent Comparer Method
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; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Text; | |
using System.Threading.Tasks; | |
namespace Item137_Sort | |
{ | |
/// <summary> | |
/// C# 2000 things | |
/// https://csharp.2000things.com/2010/11/01/137-sorting-an-array-using-an-independent-comparer-method/ | |
/// #137 – Sorting an Array Using an Independent Comparer Method | |
/// Instead of extending a type to implement IComparable to allow sorting, you can create a separate class | |
/// that knows how to compare objects of that type and use the new class to do the sorting. | |
/// | |
/// Here’s an example of sorting objects of type Person using a custom Compare method. To start with, | |
/// we define a new class that implements IComparer. | |
/// </summary> | |
class Person | |
{ | |
public string FirstName { get; set; } | |
public string LastName { get; set; } | |
public Person(string firstName, string lastName) | |
{ | |
FirstName = firstName; | |
LastName = lastName; | |
} | |
} | |
/// <summary> | |
/// | |
/// </summary> | |
public class PersonSorter : IComparer | |
{ | |
public int Compare(object o1, object o2) | |
{ | |
Person p1 = o1 as Person; | |
Person p2 = o2 as Person; | |
// Sort by LastName, then by FirstName (ignore case) | |
int compare = p1.LastName.ToLower().CompareTo(p2.LastName.ToLower()); | |
if (compare == 0) | |
{ | |
compare = p1.FirstName.ToLower().CompareTo(p2.FirstName.ToLower()); | |
} | |
return compare; | |
} | |
} | |
class Program | |
{ | |
/// <summary> | |
/// Now we can sort using this compare function by passing an instance of the IComparer | |
/// class into the Sort method. | |
/// </summary> | |
/// <param name="args"></param> | |
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, new PersonSorter()); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment